7月5日
今天完成了二路归并排序,下面是我的源代码
#include<iostream>
using namespace std;
int n;
int* a; // 定义为指针,用于动态分配内存
void Merge(int a[], int t[], int low, int mid, int high) {
int i = low, j = mid + 1, k = low;
while (i <= mid && j <= high) {
if (a[i] < a[j])
t[k++] = a[i++];
else
t[k++] = a[j++];
}
while (i <= mid)
t[k++] = a[i++];
while (j <= high)
t[k++] = a[j++];
for (int idx = low; idx <= high; ++idx) {
a[idx] = t[idx];
}
}
void prints(int s[], int n) {
for (int t = 0; t < n; ++t) {
cout << s[t];
if (t == n - 1) {
cout << endl;
}
else {
cout << " ";
}
}
}
void MSort(int a[], int t[], int low, int high) {
if (low < high) {
int mid = (low + high) / 2;
MSort(a, t, low, mid);
MSort(a, t, mid + 1, high);
Merge(a, t, low, mid, high);
prints(a, n);
}
}
int main() {
while (cin >> n) {
a = new int[n]; // 动态分配内存
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
int* t = new int[n]; // 动态分配内存
MSort(a, t, 0, n - 1);
delete[] a; // 释放动态分配的内存
delete[] t; // 释放动态分配的内存
}
return 0;
}