C语言实现合并排序算法。要排序的整型数组元素可以用随机数生成器生成,运行程序,分别记录对十万,一百万,一千万,五千万个数据排序所用的时间,列出表格显示统计出来的时间。并单独显示一个100个数据的排序结果。
时间: 2024-03-24 18:37:29 浏览: 30
好的,我可以帮你实现这个算法,以下是C语言的合并排序实现:
```c
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
void merge(int arr[], int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
int L[n1], R[n2];
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1+ j];
i = 0;
j = 0;
k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
void mergeSort(int arr[], int l, int r)
{
if (l < r)
{
int m = l+(r-l)/2;
mergeSort(arr, l, m);
mergeSort(arr, m+1, r);
merge(arr, l, m, r);
}
}
int main()
{
int n, i;
clock_t start_time, end_time;
double time_used;
printf("Enter the size of the array: ");
scanf("%d", &n);
int arr[n];
for (i = 0; i < n; i++)
{
arr[i] = rand() % 1000; // 随机生成整数
}
// 十万数据排序所用时间
start_time = clock();
mergeSort(arr, 0, 99999);
end_time = clock();
time_used = ((double) (end_time - start_time)) / CLOCKS_PER_SEC;
printf("Time taken for 100,000 data: %f seconds\n", time_used);
// 一百万数据排序所用时间
start_time = clock();
mergeSort(arr, 0, 999999);
end_time = clock();
time_used = ((double) (end_time - start_time)) / CLOCKS_PER_SEC;
printf("Time taken for 1,000,000 data: %f seconds\n", time_used);
// 一千万数据排序所用时间
start_time = clock();
mergeSort(arr, 0, 9999999);
end_time = clock();
time_used = ((double) (end_time - start_time)) / CLOCKS_PER_SEC;
printf("Time taken for 10,000,000 data: %f seconds\n", time_used);
// 五千万数据排序所用时间
start_time = clock();
mergeSort(arr, 0, 49999999);
end_time = clock();
time_used = ((double) (end_time - start_time)) / CLOCKS_PER_SEC;
printf("Time taken for 50,000,000 data: %f seconds\n", time_used);
// 取100个数据排序
printf("\nSorted array of 100 numbers:\n");
int smallArr[100];
for (i = 0; i < 100; i++)
{
smallArr[i] = rand() % 1000; // 随机生成整数
printf("%d ", smallArr[i]);
}
mergeSort(smallArr, 0, 99);
printf("\n\nSorted array of 100 numbers in ascending order:\n");
for (i = 0; i < 100; i++)
{
printf("%d ", smallArr[i]);
}
return 0;
}
```
输出结果将包括每个数组大小所需的时间,以及100个随机数的排序结果。
注意:由于排序大量数据可能需要一些时间,请耐心等待程序完成。
阅读全文