用C++完成两种排序算法: 建立10000个随机整数数组,排序后输出排序结果。 排序算法:选择排序,冒泡排序,插入排序,计数排序,基数排序,快速排序,归并排序,堆排序,桶排序,希尔排序,锦标赛排序
时间: 2024-05-08 10:21:30 浏览: 147
这里给出选择排序和快速排序的C代码示例:
选择排序:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ARRAY_SIZE 10000
void selection_sort(int arr[], int n) {
int i, j, min_idx;
for (i = 0; i < n - 1; i++) {
min_idx = i;
for (j = i + 1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
int main() {
int arr[ARRAY_SIZE];
srand(time(NULL));
for (int i = 0; i < ARRAY_SIZE; i++) {
arr[i] = rand();
}
selection_sort(arr, ARRAY_SIZE);
for (int i = 0; i < ARRAY_SIZE; i++) {
printf("%d ", arr[i]);
}
return 0;
}
```
快速排序:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ARRAY_SIZE 10000
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++;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
int temp = arr[i + 1];
arr[i + 1] = arr[high];
arr[high] = temp;
return (i + 1);
}
void quick_sort(int arr[], int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
quick_sort(arr, low, pi - 1);
quick_sort(arr, pi + 1, high);
}
}
int main() {
int arr[ARRAY_SIZE];
srand(time(NULL));
for (int i = 0; i < ARRAY_SIZE; i++) {
arr[i] = rand();
}
quick_sort(arr, 0, ARRAY_SIZE - 1);
for (int i = 0; i < ARRAY_SIZE; i++) {
printf("%d ", arr[i]);
}
return 0;
}
```
阅读全文