Merge算法的两种接口(C语言)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cheshepin/article/details/62890108

1.一种是在三个数组中实现,即把两个有序的数组合并到另一个数组中。

代码如下:

void Merge(int *A, int f, int m, int e){
	int temp[e-f+1];
	int i,first=f,last=m+1;
	for(i=0;i<(e-first+1)&&f<=m&&last<=e;i++){
		
			if(A[f]<=A[last]) {
				temp[i]=A[f];
				f++;
			}
			else {
				temp[i]=A[last];
				last++;
			}	
	}
	
	while(f>m&&last<=e){
		temp[i]=A[last];
		i++;
		last++;
	}
	
	while(f<=m&&last>e){
		temp[i]=A[f];
		i++;
		f++;
	}

	for(i=0;first<=e;i++,first++){
		A[first]=temp[i];
	}
		
}

2.第二种是在一个数组内完成的,即在一个数组中连续的,有序的两部分有序地合并起来。

代码如下:

void Merge(int *a,int a_length,int *b,int b_length,int *c){//a,b为有序数组,c为合并数组 
	int i,al,bl;
	for(i=0,al=0,bl=0;al<a_length&&bl<b_length;i++){
		if(a[al]<=b[bl]){
			c[i]=a[al];
			al++;
		}
		else{
			c[i]=b[bl];
			bl++;
		}
	} 
	
	while(al<a_length){
		c[i]=a[al];
		i++;
		al++; 
		return ;
	}
	
	while(bl<b_length){
		c[i]=b[bl];
		i++;
		bl++;
		return ; 
	}
}


猜你喜欢

转载自blog.csdn.net/cheshepin/article/details/62890108