#include<iostream> usingnamespace std; constint N = 1e6+10; int q[N]; int n;
voidquick_sort(int q[],int l,int r){ if (l >= r) return ; //递归出口 int i = l - 1; //左右指针 int j = r + 1; int x = q[l + r >> 1]; //位运算,比直接除以2更快,相当于除以2的一次方 while (i < j){ do i++;while (q[i] < x); do j--;while (q[j] > x); if (i < j) swap(q[i],q[j]); } quick_sort(q,l,j); //这里也可使用i做分界,不过参数会发生变化 quick_sort(q,j+1,r); }
intmain(){ scanf("%d",&n); for (int i = 0;i < n;i++) scanf("%d",&q[i]); //scanf比cin更快 quick_sort(q,0,n - 1); for (int i = 0;i < n;i++) printf("%d ",q[i]); return0; }
voidmerge_sort(int q[],int l, int r ){ if (l >= r) return ; int mid = l + r >> 1; //将数组一分为二 merge_sort(q,l,mid),merge_sort(q,mid+1,r); //用归并排序将两部分数组给排好序 int k = 0, i = l , j = mid + 1; //进行一个数组的合并 while (i <= mid && j <= r){ if ( q[i] < q[j] ) temp[k++] = q[i++]; else temp[k++] = q[j++]; } while (i <= mid) temp[k++] = q[i++]; //将没合并完的后半部分直接接上去 while (j <= r) temp[k++] = q[j++]; for (i = l,j = 0;i<=r;i++,j++) q[i] = temp[j]; //赋值给原数组 }
intmain(){ scanf("%d",&n); for (int i = 0;i < n;i++) scanf("%d",&q[i]); merge_sort(q,0,n - 1); for (int i = 0;i < n;i++) printf("%d ",q[i]); return0; }