# 归并排序（非原地版）

``````#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;
}``````

(0)
(0)

0条

© 2014 mamicode.com 版权所有 京ICP备13008772号-2