【源代码】严蔚敏数据结构算法C++(十八)排序——归并排序

日常说明:有错误欢迎大家指正。另外本博客所有的代码博主编写后均调试通过。重要提醒!!!!博主使用的是VS2017,如果有低版本的小伙伴最好新建空项目将此代码复制上去。
更多算法请关注我的算法专栏https://blog.csdn.net/column/details/20417.html
有朋友反映让我多加备注,我觉得除非特别惊艳的方法需要说明外,这些基本的方法是容易明白的,当然前提是先搞懂算法的基本思想,希望对你们有用。

运行结果
MergeSort.h

#pragma once
#include<iostream>
using namespace std;


class MergeSort
{
public:
    MergeSort();
    void Merge(int arr[], int low, int mid, int high,int temp[]);
    void MergeSplit(int arr[], int low, int high,int temp[]);
    void Merge_sort(int arr[],  int high,int temp[]);
};

MergeSort.cpp

#include "MergeSort.h"


MergeSort::MergeSort()
{
    return;
}

void MergeSort::Merge(int arr[],int low,int mid,int high,int temp[])
{
    int k = 0;
    int i = low;
    int j = mid + 1;
    while (i<=mid&&j<=high)
    {
        if (arr[i]<=arr[j])
        {
            temp[k++] = arr[i++];
        }
        else
        {
            temp[k++] = arr[j++];
        }
    }
    while (i<=mid)
    {
        temp[k++] = arr[i++];
    }
    while (j<=high)
    {
        temp[k++] = arr[j++];
    }
    for (int m = low,n =0; m <= high; m++,n++)
    {
        arr[m] = temp[n];
    }
}

void MergeSort::MergeSplit(int arr[],int low,int high,int temp[])
{
    int mid = (low + high) / 2;
    if (low<high)
    {
        MergeSplit(arr, low, mid,temp);
        MergeSplit(arr, mid + 1, high,temp);
        Merge(arr, low, mid, high,temp);
    }

}

void MergeSort::Merge_sort(int arr[],int high,int temp[])
{
    MergeSplit(arr,0,high,temp);
}

int main()
{
    MergeSort MSort;
    int length;
    cout << "请输入数组元素个数:";
    cin >> length;
    int *temp = new int[length];
    int *values = new int[length];
    cout << "请输入数据元素:";
    for (int i = 0; i < length; i++)
    {
        cin >> values[i];
    }
    cout << endl;
    cout << "归并排序后:";
    MSort.Merge_sort(values, length - 1,temp);
    for (int n = 0; n <length; n++)
    {
        cout << values[n]<<" ";
    }
    free(temp);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/handoking/article/details/80469045