#include<iostream> using namespace std; #define ElemType int const int Maxn=105; int Partition(ElemType A[],int low,int high){ ElemType pivot=A[low]; int i=low,j=high; while(i<j){ while(i<j&&A[j]>=pivot)j--; A[i]=A[j]; while(i<j&&A[i]<=pivot)i++; A[j]=A[i]; } A[i]=pivot; return i; } void QuickSort(ElemType A[],int low,int high){ if(low<high){ int pivotPos=Partition(A,low,high); QuickSort(A,low,pivotPos-1); QuickSort(A,pivotPos+1,high); } } //时间:最好和平均O(n*log2(n)) 最坏O(n^2) //空间:最好和平均O(log2(n)) 最坏O(n) //不稳定 void Merge(ElemType A[],int low,int mid,int high){ int i,j,k; ElemType *B=new ElemType[Maxn]; for(k=low;k<=high;k++)B[k]=A[k]; for(i=low,j=mid+1,k=low;i<=mid&&j<=high;k++){ if(B[i]<=B[j]) A[k]=B[i++]; else A[k]=B[j++]; } while(i<=mid)A[k++]=B[i++]; while(j<=high)A[k++]=B[j++]; delete[] B; } void MergeSort(ElemType A[],int low,int high){ if(low<high){ int mid=(low+high)/2; MergeSort(A,low,mid); MergeSort(A,mid+1,high); Merge(A,low,mid,high); } } //时间:O(n*log2(n)) //空间:O(n) //稳定 int main(){ int n; cin>>n; ElemType arr[Maxn]; for(int i=0;i<n;i++){ cin>>arr[i]; } MergeSort(arr,0,n-1); for(int i=0;i<n;i++){ cout<<arr[i]<<" "; } return 0; } //12 //8 2 9 3 23 7 2 6 4 1 16 7
来源:https://www.cnblogs.com/lyt888/p/12540108.html