归并排序C++实现——基于数组的

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

归并排序C++实现——基于数组的
/关于归并排序理论知识网上应该也很详细了,我在这里就分享一下自己的代码实现,有错误的地方欢迎大家指出/

#include <iostream>
//能不用using namespace std 就尽量不用;
using std::cout;
using std::endl;
using std::cin;

//high is the index of array
//对已排好的两个数组进行合并
void merge(int *arr, int low, int mid, int high)
{
    int i = low, j = mid + 1;
    int count = 0;
    int *data = new int[high - low + 1];
    for (i = low, j = mid + 1; i <= mid && j <= high;)
    {
        if (arr[i] <= arr[j])
        {
            data[count++] = arr[i];
            i++;
        }
        else
        {
            data[count++] = arr[j];
            j++;
        }
    }
    if (i <= mid)
    {
        for (; i <= mid; i++)
        {
            data[count++] = arr[i];
        }
    }
    else
    {
        for (; j <= high; j++)
        {
            data[count++] = arr[j];
        }
    }
    i = low;
    for (int k = 0; k < count&&i<=high; k++,i++)
    {
        arr[i] = data[k];
    }
    delete[] data;
}
//分而治之,将长数组一直进行二等分,当分到只剩一个时返回
void Msort(int* arr, int low, int high)
{
    if (low >= high)
    {
        return;
    }
    int mid = (low + high) / 2;
    Msort(arr, low, mid);
    Msort(arr, mid+1, high);
    merge(arr, low, mid, high);
}

int main()
{
    int len;
    cout<< "Please enter the length of array you want to sort : ";
    cin >> len;
    int *arr = new int[len];
    cout << "The data is : ";
    for (int i = 0; i < len; i++)
    {
        cin >> arr[i];
    }
    Msort(arr, 0, len - 1);
    cout << "After sort : ";
    for (int i = 0; i < len; i++)
    {
        cout << arr[i] << " ";
    }
    cout << endl;
    system("pause");
    return 0;
}
阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页