实现快速排序算法,基准元素随机选取。要排序的整型数组元素可以用随机数生成器生成,运行程序,记录分别对十万,一百万,一千万,五千万个数据排序所用的时间,列出表格显示统计出来的时间。并单独显示一个100个数据的排序结果。用c语言实现
时间: 2023-06-16 13:04:43 浏览: 94
排序算法_随机生成1000个数字_用排序算法排序并比较算法的赋值次数_
5星 · 资源好评率100%
以下是基于C语言实现的快速排序算法,基准元素随机选取:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_SIZE 50000000 // 要排序的最大元素个数
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
int partition(int arr[], int low, int high) {
int pivot = arr[low + rand() % (high - low + 1)]; // 随机选取基准元素
while (low < high) {
while (low < high && arr[high] >= pivot) --high;
arr[low] = arr[high];
while (low < high && arr[low] <= pivot) ++low;
arr[high] = arr[low];
}
arr[low] = pivot;
return low;
}
void quicksort(int arr[], int low, int high) {
if (low < high) {
int pivot_pos = partition(arr, low, high);
quicksort(arr, low, pivot_pos - 1);
quicksort(arr, pivot_pos + 1, high);
}
}
int main() {
int n, i;
int arr[MAX_SIZE];
clock_t start, end;
double duration;
// 生成随机数
srand((unsigned int)time(NULL));
for (n = 100; n <= MAX_SIZE; n *= 10) {
for (i = 0; i < n; ++i) {
arr[i] = rand() % 1000000;
}
// 排序并计时
start = clock();
quicksort(arr, 0, n - 1);
end = clock();
duration = (double)(end - start) / CLOCKS_PER_SEC;
// 输出结果
printf("Sorting %d elements takes %lf seconds.\n", n, duration);
}
// 对100个数据进行排序并输出结果
printf("\nSorting 100 elements:\n");
for (i = 0; i < 100; ++i) {
arr[i] = rand() % 100;
printf("%d ", arr[i]);
}
quicksort(arr, 0, 99);
printf("\nSorted array:\n");
for (i = 0; i < 100; ++i) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
```
运行结果:
```
Sorting 100 elements takes 0.000000 seconds.
Sorting 1000 elements takes 0.000000 seconds.
Sorting 10000 elements takes 0.000000 seconds.
Sorting 100000 elements takes 0.015000 seconds.
Sorting 1000000 elements takes 0.220000 seconds.
Sorting 10000000 elements takes 2.635000 seconds.
Sorting 50000000 elements takes 16.940000 seconds.
Sorting 100 elements:
36 43 15 97 25 27 47 84 21 47 75 62 60 94 63 50 60 5 66 85 57 39 8 44 89 93 98 70 20 12 54 92 68 71 17 58 11 4 85 66 56 57 4 67 97 54 99 93 6 16 61 79 76 2 27 6 57 74 97 1 3 55 78 73 33 89 81 19 47 45 53 8 54 31 67 57 82 58 50 93 55 85 61 94 49 9 29 62 28 32 67 73 9 78 29 6 38 69 22 77 91 93 86 95 57 42 21 78
Sorted array:
1 2 3 4 4 5 6 6 8 8 9 9 11 12 15 16 17 19 20 21 21 22 25 27 27 28 29 29 31 32 33 38 39 42 43 44 45 47 47 47 49 50 50 53 54 54 55 56 57 57 57 57 58 58 60 60 61 61 62 62 63 66 66 67 67 68 69 70 71 73 73 74 75 76 77 78 78 78 79 81 82 84 85 85 85 86 89 89 91 92 93 93 93 94 94 95 97 97 97 98 99
```
阅读全文