C++实现归并排序
#include <iostream>
using namespace std;
int* mergeSort(int* a, int n) {
if (n == 1) {
return a;
}
int leftMid = (0 + n - 1) / 2;
int rightMid = (0 + n - 1) / 2 + 1;
int leftA_length = leftMid - 0 + 1;
int rightA_length = n - rightMid;
int* leftA = new int[leftA_length];
int* rightA = new int[rightA_length];
for (int i = 0; i < leftA_length; ++i) {
leftA[i] = a[i];
}
for (int i = leftA_length; i < n; ++i) {
rightA[i - leftA_length] = a[i];
}
leftA = mergeSort(leftA, leftA_length);
rightA = mergeSort(rightA, rightA_length);
for(int i = 0, leftA_index = 0, rightA_index = 0; i < n; ++i) {
if (leftA_index >= leftA_length) {
a[i] = rightA[rightA_index];
++rightA_index;
continue;
}
if (rightA_index >= rightA_length) {
a[i] = leftA[leftA_index];
++leftA_index;
continue;
}
if (leftA[leftA_index] >= rightA[rightA_index]) {
a[i] = rightA[rightA_index];
++rightA_index;
}
else {
a[i] = leftA[leftA_index];
++leftA_index;
}
}
delete [] leftA;
delete [] rightA;
return a;
}
int main(int argc, const char * argv[]) {
int m;
cin >> m;
while((--m) >= 0) {
int n;
cin >> n;
int* a = new int[n];
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
a = mergeSort(a, n);
for (int i = 0; i < n; ++i) {
cout << a[i] << " ";
}
cout << endl;
delete [] a;
}
}
文章评论