问题:子数组a[0:k-1]和a[k,n-1]已排序,将这两个数组合并为一个有序的数组,要求时间复杂度为O(n),并且只能用O(1)的空间复杂度。
#include <stdio.h> //int a[11] = {2,4,5,9,19,1,2,3,4,10,11}; int a[11] = {1,2,3,4,5,6,7,8,9,10,11}; int k=5; int n = 11; int bin_search(int *a,int key,int s,int e) { int l = s; int h = e; int m = 0; while(l<h-1) { m = l+(h-l)/2; if(a[m]>key) h = m-1; else l = m; } if(a[h]<= key) return h; else if(a[l]<=key) return l; else return -1; } //shift a[s..e] to right k steps circlly. void circle_right_shift(int *a,int s,int e,int k) { int i = 0; int j = 0; for(i=0;i<k;i++) { int tmp = a[e]; for(j=e;j>s;j--) a[j] = a[j-1]; a[s] = tmp; } } int main() { int i = 0; int j = k; while(i<j && j<n) { int p = bin_search(a,a[i],j,n-1); if(p!=-1) { circle_right_shift(a,i,p,p-j+1); i += p-j+2; j = p+1; } else i++; } for(i=0;i<n;i++) printf("%d/n",a[i]); }