用c语言实现实现合并排序算法。要排序的整型数组元素可以用随机数生成器生成,运行程序,分别记录对十万,一百万,一千万,五千万个数据排序所用的时间,列出表格显示统计出来的时间。并单独显示一个100个数据的排序结果。
时间: 2024-05-16 12:14:45 浏览: 10
以下是使用 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;
int *arr;
clock_t start, end;
printf("Enter number of elements to be sorted: ");
scanf("%d", &n);
arr = (int *) malloc(n * sizeof(int));
// Generate n random integers
srand(time(NULL));
for (i = 0; i < n; i++) {
arr[i] = rand() % n;
}
// Sort and measure time taken
start = clock();
mergeSort(arr, 0, n - 1);
end = clock();
// Print time taken
printf("Time taken to sort %d elements: %f seconds\n", n, ((double) (end - start)) / CLOCKS_PER_SEC);
// Print first 100 sorted elements
printf("First 100 sorted elements:\n");
for (i = 0; i < 100; i++) {
printf("%d ", arr[i]);
}
printf("\n");
free(arr);
return 0;
}
```
我们使用 `clock()` 函数来测量排序所需的时间。该函数返回程序运行的时钟周期数,我们可以用 `CLOCKS_PER_SEC` 来将其转换为秒。
我们还使用 `rand()` 函数来生成随机整数。在实际的使用中,您可能希望使用更高级别的随机数生成器来生成更好的随机数。
最后,我们在控制台输出了排序后的前 100 个元素,以便您可以检查排序是否正确。
您可以在程序中更改 `n` 的值以测试不同大小的输入。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)