首页 > 代码库 > 归并排序

归并排序

归并排序是基于分治思想的排序,一递增排序为例:
首先将数组平分为两份,将左侧递增排序,右侧递增排序,
然后将两侧归并起来,使整体递增有序。

示例代码如下:

#include<stdio.h>
#include<stdlib.h>
#define Elemtype int
Elemtype *B;
void merge(Elemtype A[],int low,int mid,int high)
{
	
	for(int i=low;i<=high;i++)
	{
		B[i]=A[i];
	}
	int i=low,j=mid+1;
	int k=low;
	while(i<=mid&&j<=high)
	{
		if(B[i]<B[j])
		{
			A[k++]=B[i++];
		}
		else
		{
			A[k++]=B[j++];
		}
	}
	while(i<=mid)A[k++]=B[i++];
	while(j<=high)A[k++]=B[j++];

}
void mergesort(Elemtype A[],int low,int high)
{
	int mid=(low+high)/2;
	if(low<high)
	{
		mergesort(A,low,mid);
		mergesort(A,mid+1,high);
		merge(A,low,mid,high);
	}
}
int main()
{
	Elemtype A[12]={1,3,24,55,43,28,2,3,5,6,6,54};
	B=(Elemtype*)malloc(sizeof(Elemtype)*12);
	mergesort(A,0,11);
	for(int i=0;i<12;i++)
	{
		printf("%d ",A[i]);
	}
}


归并排序