View Code
1 #include <iostream> 2 #include <cassert> 3 #include <cmath> 4 using namespace std; 5 6 //数组反转 7 void reverse(int *a,int aLength) 8 { 9 assert(a); 10 int i=0; 11 int j=aLength-1; 12 while(i<j && i<aLength && j>0) 13 { 14 swap(a[i],a[j]); 15 i++; 16 j--; 17 } 18 } 19 20 //三次反转实现数组旋转 21 //数组a长度为aLength,将a[0...pos-1]和 22 //a[pos...aLength-1]作位置交换 23 void exchange(int *a,int aLength,int pos) 24 { 25 assert(a); 26 reverse(a,pos); 27 reverse(a+pos,aLength-pos); 28 reverse(a,aLength); 29 } 30 31 //通过旋转实现merge 32 void Merge(int *a,int aLength,int pos) 33 { 34 assert(a && aLength>0 && pos<=aLength); 35 int i=0; 36 int j=pos; 37 while (j<aLength && i<j) 38 { 39 while (i<j && a[i]<=a[j]) 40 { 41 i++; 42 } 43 int maxMove=0; 44 while (j<aLength && a[i]>a[j]) 45 { 46 maxMove++; 47 j++; 48 } 49 exchange(a+i,j-i,j-i-maxMove); 50 i+=maxMove; 51 } 52 } 53 54 void print(int *a,int aLength) 55 { 56 for (int i=0;i<aLength;i++) 57 { 58 cout<<a[i]<<" "; 59 } 60 cout<<endl; 61 } 62 int main() 63 { 64 const int aLength=8; 65 int a[aLength]={1,6,8,19,2,3,23,35}; 66 Merge(a,aLength,4); 67 print(a,aLength); 68 }
参考文章:http://www.cppblog.com/converse/archive/2008/09/28/63008.html