`
GongQi
  • 浏览: 100993 次
  • 性别: Icon_minigender_1
  • 来自: 大连
社区版块
存档分类
最新评论

空间复杂度O(1)的归并问题

 
阅读更多
最近百度实习生笔试题里考了这个,要求归并算法里空间复杂度为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]);
}
0
3
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics