计数排序随机生成n个数据,画出随n的增长时间变化的图像 C++实现
时间: 2024-05-14 08:12:34 浏览: 60
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_NUM 1000000
void countSort(int arr[], int n) {
int count[MAX_NUM] = {0};
int output[n];
for (int i = 0; i < n; i++) {
count[arr[i]]++;
}
for (int i = 1; i < MAX_NUM; i++) {
count[i] += count[i - 1];
}
for (int i = n - 1; i >= 0; i--) {
output[count[arr[i]] - 1] = arr[i];
count[arr[i]]--;
}
for (int i = 0; i < n; i++) {
arr[i] = output[i];
}
}
int main() {
int n;
printf("请输入数据个数n:");
scanf("%d", &n);
int arr[n];
srand(time(NULL));
for (int i = 0; i < n; i++) {
arr[i] = rand() % MAX_NUM;
}
clock_t start = clock();
countSort(arr, n);
clock_t end = clock();
double time_used = (double)(end - start) / CLOCKS_PER_SEC;
printf("排序用时:%f秒\n", time_used);
return 0;
}
```
阅读全文