Divided thinking: recursion, so that the first half and the second half of the order, and then Merge. Time Complexity o (nlgn)
1#include <iostream>2 usingstd::cout;3 4 voidGsort (int*a,intFrontintRear)5 {6 if(front>=rear)return;//border Processing7 if(front+1==rear)//boundary Processing8 {9 if(a[rear]<a[front])Ten{inttemp=a[front];a[front]=a[rear];a[rear]=a[front];} one return; a } - intM= (front+rear)/2; - Gsort (a,front,m); theGsort (a,m+1, rear); - int*p=New int[rear-front+1];//opens New space, sorting the left and right groups into new space - intpp=0, p1=front,p2=m+1; - while(1) + { - if(p1>m && P2>rear) break; + if((a[p1]<a[p2] | | P2>rear) && p1<=m) p[pp++]=a[p1++]; a Elsep[pp++]=a[p2++]; at } - for(intI=0; i<rear-front+1; I++) a[i+front]=p[i]; - Delete[] p; - } - - intMain () in { - inta[]={ one,5,Wuyi,0,531,5,-1, $,4,-5, $,4}; to intlen=sizeof(a)/sizeof(int); +Gsort (a,0, len-1); - for(intI=0; I<len;i++) cout<<a[i]<<" "; thecout<<"\ n"; * $ return 0;Panax Notoginseng}
Summary of sorting methods (iii) merge sort