就地歸併排序inplacMergeSort,空間複雜度O(1)
阿新 • • 發佈:2019-01-27
難度在就地歸併:說看程式碼及註釋。與上篇文章有點類似。
//============================================================================ //@lgh原創 //============================================================================ #include <iostream> #include <algorithm> #include <stdio.h> #include <string.h> using namespace std; void pr_arr(char* first,char*last) { while(first!=last) { printf("%c",*first++); } } void swap(char*s1,char*s2) { if(*s1!=*s2) { char t=*s1; *s1=*s2; *s2=t; } } //找出第一個大於等於val的值的位置 char* lower_bound(char*first,char*last,int val) { int len=last-first; while(len>0) { int half=len>>1; char*mid=first+half; if(*mid < val) { first=mid+1; len=len-half-1; } else len=half; } return first; } //找出第一個大於val的元素的位置。 char* upper_bound(char*first,char*last,char val) { int len=last-first; while(len>0) { int half=len>>1; char* mid=first+half; if(*mid<=val) { first=mid+1; len=len-half-1; } else{ len=half; } } return first; } //輾轉相除法,求最大公約數 int gcd(int m,int n) { while(n!=0) { int t=n; n=m%n; m=t; } return m; } //shift偏移量,這裡==mid-begin void rotate_recyle(char*begin,char*end,char*initial,int shift) { char t=*initial; int len=end-begin; char *p1=initial; //p1為初始位置 char *p2=p1+shift; //p2指向p1最後要放元素的位置,實際上就是p1+shift while(p2!=initial) { *p1=*p2; p1=p2; p2=begin+(p2-begin+shift)%len; //p2超過未尾的話,要從頭開始 } *p1=t; } /*上面 p2=begin+(p2-begin+shift)%len也可以寫成,仿STL if(end-p2>shift) p2+=shift; else p2=begin+(shift-(end-p2)); */ void rotate(char*begin,char*mid,char*end) //倒換兩個區間 { if(begin==mid || mid==end) return; int n=gcd(mid-begin,end-begin); while(n--) { rotate_recyle(begin,end,begin+n,mid-begin); } } /*思想:舉例說明: [13579,2468] 兩個區間歸併 * 區間1的長度更長,則 找出區間1的中間值5,再找出[2468]中第一個大於等於5的位置6 *即目的是分成這樣:[13,579][24,68]此時 [579] > [24] 互換區間 *得[13,24]<=[579,68],規律出來的,[13,24]、[579,68]分別是兩個子問題,遞迴OK *PS:區間2更長時,類似。 */ void inplaceMerge(char*first,char*mid,char*last) { int len1=mid-first,len2=last-mid; if(0==len1 || 0==len2) return ; if(len1+len2==2)//只有兩個元素,則 { if(*mid<*first) swap(first,mid); return; } char *firstCut, *secondCut; if(len1>len2) //區間1>區間2 { firstCut=first+(len1>>1); //區間1的中間處 secondCut=lower_bound(mid,last,*firstCut); //第一個大於等於中間處的位置 } else { secondCut=mid+(len2>>1); //區間2的中間處 firstCut=upper_bound(first,mid,*secondCut); //第一個大於中間處的位置 } //那麼此時區域[firstCut,mid)>[mid,secondCut),兩區間互換,那就中間兩塊就有序了。 rotate(firstCut,mid,secondCut); char* newMid=firstCut+(secondCut-mid); //找到分界處 inplaceMerge(first,firstCut,newMid); inplaceMerge(newMid,secondCut,last); } void inplaceMergeSort(char s[],int len) { if(s==NULL || len<=1) return; inplaceMergeSort(s,len/2); inplaceMergeSort(s+len/2,len-len/2); inplaceMerge(s,s+len/2,s+len); } int main() { char s[] ="0124683579"; int len = strlen(s); inplaceMergeSort(s,len); printf("%s \n", s); return 0; }