合并排序(归并排序)的C语言实现

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

直接上代码:

#include<stdio.h>

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];
	}	
}


void Merge_Sort(int *a,int f,int e ){
	int mid=(e+f)/2;
	if(f<e){
		Merge_Sort(a,f,mid);
		Merge_Sort(a,mid+1,e);
		Merge(a,f,mid,e);
	}	
}

int main(){
	int a[100];
	int n;//n为输入的数组的长度;
	printf("输入要排序的数组长度(小于100个)\n");
	scanf("%d",&n);
	for(int i=0;i<n;i++){
		scanf("%d",&a[i]);
	} 
	printf("未排序前数组元素顺序额为:\n");
	for(int i=0;i<n;i++){
		printf("%d ",a[i]);
	} 
	
	Merge_Sort(a,0,n-1);

	printf("\n\n排序后的数组元素顺序为:\n");	
	for(int i=0;i<n;i++){
		printf("%d ",a[i]);
	}
	printf("\n");
	getchar();	
}


猜你喜欢

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