#include<iostream>
using namespace std;
void Merge(int arr[], int L, int M, int H) {
int LEFT_SIZE = M - L;
int RIGHT_SIZE = H - M + 1;
int *left=new int[LEFT_SIZE];
int *right = new int[RIGHT_SIZE];
for (int i = 0;i < M;i++) {
left[i-L] = arr[i];
}
for (int j = M;j < H + 1;j++) {
right[j-M] = arr[j];
}
int i = 0;int j = 0;int k = L;
while (i < LEFT_SIZE && j < RIGHT_SIZE) {
if (left[i] < right[j]) {
arr[k] = left[i];
i++;
k++;
}
else {
arr[k] = right[j];
j++;
k++;
}
}
while (i < LEFT_SIZE) {
arr[k] = left[i];
i++;
k++;
}
while (j < RIGHT_SIZE) {
arr[k] = right[j];
j++;
k++;
}
}
void mergesort(int arr[], int L, int H) {
if (L == H) {
return;
}
int M = (L + H) / 2;
mergesort(arr, L, M);
mergesort(arr, M + 1, H);
Merge(arr, L, M + 1, H);
}
int main() {
int arr[] = { 2,9,8,4,7,5,3,1 };
mergesort(arr, 0, 7);
for (int i = 0;i < 8;i++) {
cout << arr[i];
}
system("pause");
}
一个归并排序的例子(C++)
最新推荐文章于 2023-04-05 20:54:28 发布