八种排序方法(七)——归并排序

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

编译器:Xcode
编程语言:C++

源程序:

#include<iostream>
using namespace std;

void merge(int a[],int low,int mid,int high)
{
    int i,k;
    //定义一个临时数组存放传进来的无序数组排好序之后的数组
    int *temp=(int *)malloc((high-low+1)*sizeof(int));
    //将无序数组分成两个序列
    int left_low=low;
    int left_high=mid;
    int right_low=mid+1;
    int right_high=high;
    //将两个序列比较排序,小的排前
    for(k=0;left_low<=left_high && right_low<=right_high;k++)
    {
        if(a[left_low]<=a[right_low])
            temp[k]=a[left_low++];
        else
            temp[k]=a[right_low++];
    }
    //左序列如果有剩下元素未排序,加到临时数组的末尾
    if(left_low<=left_high)
    {
        for(i=left_low;i<=left_high;i++)
            temp[k++]=a[i];
    }
    //右序列如果有剩下元素未排序,加到临时数组的末尾
    if(right_low<=right_high)
    {
        for(i=right_low;i<=right_high;i++)
            temp[k++]=a[i];
    }
    //将排好序的小分组转移到原数组中
    for(i=0;i<high-low+1;i++)
    {
        a[low+i]=temp[i];
    }
    free(temp);
}

void mergeSort(int a[],int first,int last)//归并排序
{
    int mid=0;
    //将数组不停的二分分组再组合,直到每组只剩下一个元素
    if(first<last)
    {
        mid=(first+last)/2;
        mergeSort(a, first, mid);
        mergeSort(a, mid+1, last);
        merge(a,first,mid,last);
    }
}

int main()
{
    int a[10] = {43, 65, 4, 23, 6, 98, 2, 65, 7, 79};
    cout<<"归并排序:"<<endl;
    mergeSort(a, 0, 9);
    for(int i=0;i<10;i++)
        cout<<a[i]<<" ";
    cout<<endl;
    return 0;
}

运行结果:

归并排序:
2 4 6 7 23 43 65 65 79 98 
Program ended with exit code: 0

猜你喜欢

转载自blog.csdn.net/qq_39360985/article/details/78826043
今日推荐