#include <iostream>
#include <random>
using namespace std;
int merge(int *A, int low, int mid, int high)
{
int left = mid - low + 1;
int right = high - mid;
int *L = new int[left];
int *R = new int[right];
int i = 0; int j = 0; int k = low;
while (i<left)
{
L[i] = A[low + i];
++i;
}
while (j<right)
{
R[j] = A[mid + 1 + j];
j++;
}
while (i<left && j<right)
{
if (L[i]<R[j])
{
A[k++] = L[i++];
}
else
{
A[k++] = R[j++];
}
}
while (i< left)
{
A[k++] = L[i++];
}
while (j<right)
{
A[k++] = R[j++];
}
delete[] L;
delete[] R;
return 0;
}
int merge_sort(int *A, int low, int high)
{
if (low < high)
{
int mid = (low + high) / 2;
merge_sort(A, low, mid);
merge_sort(A, mid + 1, high);
merge(A, low, mid, high);
}
return 0;
}
int main()
{
default_random_engine e;
int n = 0;
cin >> n;
int *A = new int[n];
for (int i = 0; i < 200; i++)
{
A[i] = e();
}
merge_sort(A, 0, n - 1);
for (int i = 0; i < 200; ++i)
{
cout << A[i] << " ";
}
return 0;
}
归并排序
最新推荐文章于 2023-12-11 10:45:47 发布