#include<stdio.h>
#include<malloc.h>
#include<time.h>
#define MAX 10
int* Creat_Array()
{
int* arr = (int *)malloc(sizeof(int) * MAX);
srand((unsigned int)time(NULL));
for (int i = 0; i < MAX; i++)
{
arr[i] = rand() % MAX;
}
return arr;
}
void Merge(int a[], int start, int mid, int end, int temp[])
{
int i_start = start;
int i_end = mid;
int j_start = mid + 1;
int j_end = end;
int length = 0;
while (i_start <= i_end && j_start <= j_end)
{
if (a[i_start] <= a[j_start])
{
temp[length] = a[i_start];
i_start++;
length++;
}
else
{
temp[length] = a[j_start];
j_start++;
length++;
}
}
while (i_start <= i_end)
{
temp[length] = a[i_start];
i_start++;
length++;
}
while (j_start <= j_end)
{
temp[length] = a[j_start];
j_start++;
length++;
}
for (int i = 0; i < length; i++)
{
a[start+i] = temp[i];
}
}
void Merge_Sort(int a[], int start, int end, int *temp)
{
if (start >= end)
{
return;
}
int mid = (start + end) / 2;
Merge_Sort(a, start, mid, temp);
Merge_Sort(a, mid+1, end, temp);
Merge(a, start, mid, end, temp);
}
void Show(int a[])
{
for (int i = 0; i < MAX; i++)
{
printf("%d ", a[i]);
}
printf("\n");
}
int main(int argc, char const *argv[])
{
int* a = Creat_Array();
int* temp = Creat_Array();
Show(a);
Merge_Sort(a, 0, MAX-1, temp);
Show(a);
return 0;
}
数据结构-排序算法之归并排序(C语言实现)
最新推荐文章于 2024-06-05 15:10:59 发布