1. 程式人生 > >圖解希爾排序

圖解希爾排序

題目描述
給出一個數據序列,使用希爾排序演算法進行從小到大的排序。

間隔gap使用序列長度迴圈除2直到1。

輸入
第一行輸入t,表示有t個測試示例

第二行輸入n,表示第一個示例有n個數據

第三行輸入n個數據,都是正整數,資料之間用空格隔開

以此類推

輸出
對每個示例,輸出希爾排序的每一趟排序結果

樣例輸入
2
6
111 22 6 444 333 55
8
77 555 33 1 444 77 666 2222

樣例輸出
6 111 22 6 444 333 55
6 6 22 55 111 333 444
8 77 77 33 1 444 555 666 2222
8 33 1 77 77 444 555 666 2222
8 1 33 77 77 444 555 666 2222
#include<iostream>
using namespace std;

void display(int *a,int n)
{
    int i;
    cout<<n<<" ";
    for(i=0;i<n;i++)
    {
        cout<<a[i];
        if(i<=n-2)
            cout<<" ";
    }
    cout<<endl;
}

void ShellSort(int *a,int low,int high)
{
    int
temp;int i,j; int gap=high-low+1; for(gap=gap/2;gap>=1;gap=gap/2) { for(i=low+gap;i<high;i=i++)//直接插入排序 { if(a[i]<a[i-gap]) { temp=a[i]; j=i-gap; do{ a[j+gap]=a[j]; j=j-gap; }while
(j>=low&&a[j]>temp); a[j+gap]=temp; } } display(a,high); } } int main() { int n;int i;int t; cin>>t; while(t--) { cin>>n; int *a=new int[n]; for(i=0;i<n;i++) cin>>a[i]; ShellSort(a,0,n); delete []a; } return 1; }