typedef int ElemType;
ElemType *B = (ElemType *)malloc((n+1)*sizeof(ElemType));//辅助数组B
//A[low...mid]和A[mid+1,high]各自有序,将两个部分归并成一个有序表。
void Merge(ElemType A[],ElemType low,ElemType mid,ElemType high){
ElemType i,j,k;
for(int k=low;k<=high;k++)
{
B[k]=A[k];//将A中所有元素复制到B中
}
//归并
for(i=low,k=low,j=mid+1;i<=mid&&j<=high;k++)
{
if(B[i]<=B[j]){
//比较B中左右两段中的元素。
A[k]=B[i++];//将较小的元素赋值到A中
}
else
{
A[k]=B[j++];
}
}
//将剩余的元素也赋值到A中
while(i<=mid)
{
A[k++]=B[i++];//若第一个表未检测完,复制
}
while(j<=high)
{
A[k++]=B[j++];//若第二个表未检测完,复制
}
}
void MergeSort(ElemType A[],ElemType low,ElemType high){
if(low<high){
//从中间划分
ElemType mid= (low+high)/2;
//对左半部分归并排序
MergeSort(A,low,mid);
//对右半部分归并排序
MergeSort(A,mid+1,high);
//归并
Merge(A,low,high);
}
}
The code of the sorting algorithm -- merge sort
Guess you like
Origin blog.csdn.net/weixin_48060069/article/details/127170797
Recommended
Ranking