快排
看了一篇灰常不错的文章,讲述了两种快排,尤其是第二种算法,能将快排对有序数列排序的复杂度降低到O(N)。
type1:(类似二分)
1 #include<stdio.h> 2 #include<iostream> 3 int partition(int arr[],int l,int r){ 4 int k = l; 5 int pivot = arr[r]; 6 for (int i = l; i < r; i++){ 7 if(arr[i] <= pivot) std::swap(arr[i],arr[k++]); 8 } 9 std::swap(arr[k],arr[r]); 10 return k; 11 } 12 void qsort(int arr[],int l,int r){ 13 if(l<r){ 14 int pivot = partition(arr,l,r); 15 qsort(arr,l,pivot-1); 16 qsort(arr,pivot+1,r); 17 } 18 } 19 int main(){ 20 int n; 21 int arr[12]; 22 scanf("%d",&n); 23 for (int i = 0;i < n; i++){ 24 scanf("%d",&arr[i]); 25 } 26 qsort(arr,0,n-1); 27 for (int i = 0;i < n; i++){ 28 printf("%d ",arr[i]); 29 } 30 }
type2:(类似三分)
1 #include<stdio.h> 2 #include<iostream> 3 #include<stdlib.h> 4 5 std::pair<int,int> partition(int arr[],int l,int r){ 6 7 int k = l; 8 int p = r; 9 for (int i = l;i < p;){ 10 if(arr[i] < arr[r]) 11 std::swap(arr[i++],arr[k++]); 12 else if(arr[i]==arr[r]) 13 std::swap(arr[i],arr[--p]); 14 else 15 i++; 16 } 17 int m = std::min(p-k,r-p+1); 18 for (int i = 0;i < m; i++){ 19 std::swap(arr[k+i],arr[r-i]); 20 } 21 return std::make_pair(k,r-p+k); 22 } 23 24 void qsort(int arr[],int l,int r){ 25 if(l<r){ 26 std::pair<int,int> pivot = partition(arr,l,r); 27 qsort(arr,l,pivot.first-1); 28 qsort(arr,pivot.second+1,r); 29 } 30 } 31 int main(){ 32 int arr[20]; 33 int n; 34 scanf("%d",&n); 35 for (int i = 0;i < n; i++){ 36 scanf("%d",&arr[i]); 37 } 38 qsort(arr,0,n-1); 39 for (int i = 0;i < n; i++){ 40 printf("%",arr[i]); 41 } 42 }
好久没敲c和c++了,果然生疏了,代码也没那么优雅了,凑合着看吧。。。
算法详情:http://segmentfault.com/a/1190000002651247?utm_source=Weibo&utm_medium=shareLink&utm_campaign=socialShare