#include <iostream>
#define NIL 666
using namespace std;
#define WUQIONG 99999
#define len 1000
void MERGE(int *A, int p, int q, int r)
{
int n1 = q - p + 1;
int n2 = r - q;
int* R = (int*)malloc(sizeof(int)*(n1 + 1));
int* L = (int*)malloc(sizeof(int)*(n2 + 1));
for (int i = 0; i < n1; i++)
{
R[i] = A[p+i];
}
for (int i = 0; i < n2; i++)
{
L[i] = A[q + 1 + i];
}
R[n1 ] = WUQIONG;
L[n2] = WUQIONG;
for (int i = 0, j = 0, k = p;k<=r;k++)
{
if (R[i] > L[j])
{
A[k] = L[j];
j++;
}
else
{
A[k] = R[i];
i++;
}
}
free(L);
free(R);
}
void MERGE_SORT(int* A,int p ,int r)
{
if (p<r)
{
int q = (r + p) / 2;
MERGE_SORT(A, p, q);
MERGE_SORT(A, q + 1, r);
MERGE(A, p, q, r);
}
}
int main()
{
int* Data = (int*)malloc(sizeof(int) * len);
srand((unsigned)time(NULL));
for (int i = 0; i < len; i++) //产生随机数
{
Data[i] = rand() % 1000;
}
for (int i = 0; i < len; i++)
{
if (i % 10 == 0)
printf("\n");
printf("%d ", Data[i]);
}
MERGE_SORT(Data, 0, len-1);
cout << endl << endl;
for (int i = 0; i < len; i++)
{
if (i % 10 == 0)
printf("\n");
printf("%d ", Data[i]);
}
}
CLRS 归并排序实现
最新推荐文章于 2024-08-12 19:27:52 发布