#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;
}
归并排序(非原地版)
Posted 言何午
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了归并排序(非原地版)相关的知识,希望对你有一定的参考价值。
以上是关于归并排序(非原地版)的主要内容,如果未能解决你的问题,请参考以下文章