最近百度实习生笔试题里考了这个,要求归并算法里空间复杂度为O(1),不能设置辅助数组
# include <stdio.h>
# define N 10
int binarySearch(int m,int* unsort ,int low,int high){
int mid;
while(low<=high){
mid=(low+high)/2;
if(unsort[mid]>m)
high=mid-1;
else if(unsort[mid]<m)
low=mid+1;
else return mid;
}
return low;
}
void merge(int * unsort,int low,int mid,int num){
int i,j,k,count=0,temp;
for(j=mid;j<num;j++)
{
i=binarySearch(unsort[j],unsort,low,mid+count-1);
temp=unsort[j];
for(k=j;k>i;k--){
unsort[k]=unsort[k-1];
}
unsort[i]=temp;
++count;
}
}
void main(){
int i,unsort[]={1,4,5,7,9,0,2,3,6,8};
merge(unsort,0,5,N);
for(i=0;i<N;i++)
printf("%d ",unsort[i]);
}