归并排序(非原地版)

Posted 言何午

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了归并排序(非原地版)相关的知识,希望对你有一定的参考价值。

#include <iostream>
using namespace std;


void merge(int* arr, int* reg, int start, int end) {
    if (start >= end)
        return;
    int left = start;
    int right = end;
    int mid = (left + right) / 2;
    merge(arr, reg, left, mid);
    merge(arr, reg, mid + 1, right);
    int start1 = left;
    int start2 = mid + 1;
    int resIdx = left;
    while (start1 <= mid && start2 <= right) {
        reg[resIdx++] = arr[start1] < arr[start2] ? arr[start1++] : arr[start2++];
    }
    while (start1 <= mid) {
        reg[resIdx++] = arr[start1++];
    }
    while (start2 <= right) {
        reg[resIdx++] = arr[start2++];
    }
    for (resIdx = start; resIdx <= end; resIdx++) {
        arr[resIdx] = reg[resIdx];
    }
}

void mergeSort(int* arr, int* reg, const int size) {
    merge(arr, reg, 0, size - 1);
}

int main() {
    int size, i;
    cin >> size;
    int *arr = new int[size];
    for (i = 0; i < size; i++) {
        cin >> arr[i];
    }
    int *reg = new int[size];
    mergeSort(arr, reg, size);
    cout << endl;
    cout << "Result:" << endl;
    for (i = 0; i < size; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
    delete [] arr;
    delete [] reg;
    return 0;
}

以上是关于归并排序(非原地版)的主要内容,如果未能解决你的问题,请参考以下文章

九种经典排序算法详解(冒泡排序,插入排序,选择排序,快速排序,归并排序,堆排序,计数排序,桶排序,基数排序)

归并排序(Merge Sort)

javascript实现非递归--归并排序

原地归并排序

5 行代码实现快速排序(简易版)

归并排序