分治思想:递归,使前一半和后一半排好序,再合并。时间复杂度O(nlgn)
1 #include <iostream> 2 using std::cout; 3 4 void gsort(int *a,int front,int rear) 5 { 6 if(front>=rear)return;//边界处理 7 if(front+1==rear)//边界处理 8 { 9 if(a[rear]<a[front]) 10 {int temp=a[front];a[front]=a[rear];a[rear]=a[front];} 11 return; 12 } 13 int m=(front+rear)/2; 14 gsort(a,front,m); 15 gsort(a,m+1,rear); 16 int *p=new int[rear-front+1];//开辟新的空间,将左右两组排序到新空间 17 int pp=0,p1=front,p2=m+1; 18 while(1) 19 { 20 if(p1>m && p2>rear)break; 21 if(( a[p1]<a[p2] || p2>rear) && p1<=m )p[pp++]=a[p1++]; 22 else p[pp++]=a[p2++]; 23 } 24 for(int i=0;i<rear-front+1;i++)a[i+front]=p[i]; 25 delete[] p; 26 } 27 28 int main() 29 { 30 int a[]={11,5,51,0,531,5,-1,46,4,-5,65,4}; 31 int len=sizeof(a)/sizeof(int); 32 gsort(a,0,len-1); 33 for(int i=0;i<len;i++)cout<<a[i]<<" "; 34 cout<<"\n"; 35 36 return 0; 37 }
原文:http://www.cnblogs.com/backinfile/p/5829526.html