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