#include <stdio.h>
#include <stdlib.h>
typedef int ElementType;
void Merge(ElementType A[], ElementType TmpArray[],
int Lpos, int Rpos, int RightEnd);
void MergeSort(ElementType A[], int N);
int min(int a, int b);
int main()
{
int A[10] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
MergeSort(A, 10);
for (int i = 0; i < 10; i++)
printf("%d ", A[i]);
}
int min(int a, int b)
{
return a < b ? a : b;
}
void MergeSort(ElementType A[], int N)
{
ElementType *TmpArray;
int SubListSize, Part1Start, Part2Start, Part2End;
TmpArray = malloc(sizeof(ElementType) * N);
if (TmpArray == NULL)
{
printf("Out of space!!!\n");
exit(0);
}
else
{
for (SubListSize = 1; SubListSize < N; SubListSize *= 2)
{
Part1Start = 0;
while (Part1Start + SubListSize < N)
{
Part2Start = Part1Start + SubListSize;
Part2End = min(N, Part2Start + SubListSize - 1);
Merge(A, TmpArray, Part1Start, Part2Start, Part2End);
Part1Start = Part2End + 1;
}
}
}
}
void Merge(ElementType A[], ElementType TmpArray[],
int Lpos, int Rpos, int RightEnd)
{
int i, LeftEnd, NumElements, TmpPos;
LeftEnd = Rpos - 1;
TmpPos = Lpos;
NumElements = RightEnd - Lpos + 1;
/*main loop*/
while (Lpos <= LeftEnd && Rpos <= RightEnd)
if (A[Lpos] <= A[Rpos])
TmpArray[TmpPos++] = A[Lpos++];
else
TmpArray[TmpPos++] = A[Rpos++];
while (Lpos <= LeftEnd) /*Copy rest of first half*/
TmpArray[TmpPos++] = A[Lpos++];
while (Rpos <= RightEnd) /*Copy rest of second half*/
TmpArray[TmpPos++] = A[Rpos++];
/*Copy TmpArray back*/
for (i = 0; i < NumElements; i++, RightEnd--)
A[RightEnd] = TmpArray[RightEnd];
}
归并排序的非递归实现
最新推荐文章于 2023-03-25 00:51:13 发布