給定N個(長整型範圍內的)整數,要求輸出從小到大排序後的結果。算法
本題旨在測試各類不一樣的排序算法在各類數據狀況下的表現。各組測試數據特色以下:數組
輸入第一行給出正整數N(≤),隨後一行給出N個(長整型範圍內的)整數,其間以空格分隔。測試
在一行中輸出從小到大排序後的結果,數字間以1個空格分隔,行末不得有多餘空格。spa
11 4 981 10 -17 0 -20 29 50 8 43 -5
-20 -17 -5 0 4 8 10 29 43 50 981
#include<cstdio> const int maxn = 100010; void Bubble_sort(long* a,int n); void Insertion_sort(long* a,int n); void Select_sort(long *a,int n); void Shell_sort(long* a,int n); void Shell_sedgewick(long* a,int n); //快排,歸併,堆排序 int main(){ int n; scanf("%d",&n); long a[maxn]; for(int i = 0; i < n; i++){ scanf("%ld",&a[i]); } //Bubble_sort(a,n); //Insertion_sort(a,n); //Select_sort(a,n); //Shell_sort(a,n); Shell_sedgewick(a,n); for(int i = 0; i < n; i++){ if(i == 0) printf("%ld",a[i]); else printf(" %ld",a[i]); } return 0; } //冒泡排序 void Bubble_sort(long *a,int n){ bool flag; long temp; for(int i = n-1; i > 0; i--){ flag = false; for(int j = 0; j < i; j++){ if(a[j] > a[j+1]){ temp = a[j]; a[j] = a[j+1]; a[j+1] = temp; flag = true; } } if(flag == false) break; } } //插入排序 void Insertion_sort(long* a,int n){ int i,j; long temp; for(i = 1; i < n; i++){ temp = a[i]; for(j = i; j > 0 && a[j - 1] > temp; j--) a[j] = a[j - 1]; a[j] = temp; } } //選擇排序 void Select_sort(long* a,int n){ int i,j,k; long temp; for( i = 0; i < n; i++){ temp = a[i]; for(j = i + 1; j < n; j++){ if(a[j] < temp){ temp = a[j]; k = j; } } a[k] = a[i]; a[i] = temp; } } //希爾-自增排序 void Shell_sort(long*a ,int n){ int i,j,d; long temp; for(d = n/2; d > 0; d /= 2){ for(i = d; i < n; i++){ temp = a[i]; for(j = i; j >= d && a[j - d] > temp; j -= d) a[j] = a[j - d]; a[j] = temp; } } } //希爾-數組排序 void Shell_sedgewick(long* a,int n){ int i,j,d,si; int sedgewick[] = {929,505,209,109,41,19,5,1,0}; long temp; for(si = 0; sedgewick[si] >= n; si++); for(; sedgewick[si] > 0; si++){ d = sedgewick[si]; for(i = d; i < n; i++){ temp = a[i]; for(j = i; j >= d && a[j - d] > temp; j -= d) a[j] = a[j - d]; a[j] = temp; } } }
void Heap_sort(long* a,int n){ long temp; int i; for(i = (n-2)/2; i >= 0; i--){ percdown(a,n,i); } for(i = n - 1; i > 0; i--){ temp = a[0]; a[0] = a[i]; a[i] = temp; percdown(a,i,0); } } void percdown(long* a,int n,int i){ long x = a[i]; int child; for(; i * 2 + 1 <= n - 1; i = child){ child = 2 * i + 1; if(child < n - 1 && a[child + 1] > a[child]) child++; if(a[child] <= x) break; else a[i] = a[child]; } a[i] = x; } void Merge_sort(long*a ,int n){ long* tmp = (long*)malloc(n*sizeof(long)); msort(a,tmp,0,n-1); free(tmp); } void msort(long*a,long* tmp,int start,int end){ int middle; if(start < end){ middle = (start+end)/2; msort(a,tmp,start,middle); msort(a,tmp,middle+1,end); merge(a,tmp,start,end,middle); } } void merge(long* a,long* tmp,int start,int end,int middle){ int l,s,r; l = start; s = start; r = middle + 1; while(l <= middle && r <= end){ if(a[l] < a[r]) tmp[s++] = a[l++]; else tmp[s++] = a[r++]; } while(l <= middle) tmp[s++] = a[l++]; while(r <= end) tmp[s++] = a[r++]; for(;start <= end; start++) a[start] = tmp[start]; }