#include<stdio.h>
#include<stdlib.h>
int MergeSort(int sourceArr[], int tempArr[], int low, int high);
int Merge(int tempArr[], int sourceArr[], int low, int mid, int high);
int main()
{
int a[10], b[10];
for (int i = 0; i < 10; i++)
a[i] = rand() % 100;
for (int i = 0; i < 10; i++)
printf("%d ", a[i]);
printf("\n");
MergeSort(a, b, 0, 9);
for (int i = 0; i < 10; i++)
printf("%d ", b[i]);
return 0;
}
int MergeSort(int sourceArr[], int tempArr[], int low, int high)
{
int mid;
if(low < high)
{
mid = (low + high) / 2;
MergeSort(sourceArr, tempArr, low, mid);
MergeSort(sourceArr, tempArr, mid + 1, high);
Merge(tempArr, sourceArr, low, mid, high);
}
return 0;
}
int Merge(int tempArr[], int sourceArr[], int low, int mid, int high)
{
int i = low, j = mid + 1, k = low;
while(i <= mid && j <= high)
{
if(sourceArr[i] < sourceArr[j])
tempArr[k++] = sourceArr[i++];
else
tempArr[k++] = sourceArr[j++];
}
while(i <= mid)
tempArr[k++] = sourceArr[i++];
while(j <= high)
tempArr[k++] = sourceArr[j++];
for (int p = low; p <= high; p++)
sourceArr[p] = tempArr[p];
return 0;
}
归并排序的递归实现(C语言)
最新推荐文章于 2024-04-19 15:37:53 发布