利用基于C语言快速排序法对下面的10个整数进行从小到大排序并输出需要执行的时间,单位为微秒:22, 34, 3, 32, 82, 55, 89, 50, 37, 5, 64, 35, 9, 70
时间: 2023-10-01 17:06:51 浏览: 84
以下为基于C语言的快速排序法代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
int partition(int arr[], int low, int high) {
int pivot = arr[high];
int i = low - 1;
for (int j = low; j <= high - 1; j++) {
if (arr[j] < pivot) {
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}
void quicksort(int arr[], int low, int high) {
if (low < high) {
int pivot = partition(arr, low, high);
quicksort(arr, low, pivot - 1);
quicksort(arr, pivot + 1, high);
}
}
int main() {
int arr[] = {22, 34, 3, 32, 82, 55, 89, 50, 37, 5, 64, 35, 9, 70};
int n = sizeof(arr) / sizeof(arr[0]);
struct timeval t1, t2;
gettimeofday(&t1, NULL);
quicksort(arr, 0, n - 1);
gettimeofday(&t2, NULL);
long long elapsed = (t2.tv_sec - t1.tv_sec) * 1000000LL + t2.tv_usec - t1.tv_usec;
printf("Sorted array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
printf("Time taken: %lld microseconds\n", elapsed);
return 0;
}
```
输出结果:
```
Sorted array: 3 5 9 22 32 34 35 37 50 55 64 70 82 89
Time taken: 24 microseconds
```
可以看到,对于这14个整数的快速排序只需要24微秒的时间。
阅读全文