2.用C++完成两种排序算法: 建立10000个随机整数数组,排序后输出排序结果。 排序算法:选择排序,冒泡排序,插入排序,计数排序,基数排序,快速排序,归并排序,堆排序,桶排序,希尔排序,锦标赛排序
时间: 2024-05-10 22:19:24 浏览: 49
下面是选择排序和快速排序的C++代码实现:
1. 选择排序
```cpp
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
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;
}
}
swap(arr[i], arr[min_idx]);
}
}
int main() {
srand(time(NULL));
int n = 10000;
int arr[n];
for (int i = 0; i < n; i++) {
arr[i] = rand();
}
selection_sort(arr, n);
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
```
2. 快速排序
```cpp
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
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 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() {
srand(time(NULL));
int n = 10000;
int arr[n];
for (int i = 0; i < n; i++) {
arr[i] = rand();
}
quick_sort(arr, 0, n-1);
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
```
阅读全文