一组数据通过直接插入排序、冒泡排序、快速排序、简单选择排序进行排序,c++ 代码实现
时间: 2023-08-14 20:06:37 浏览: 85
好的,下面是一组数据通过这四种排序算法进行排序的 C++ 代码实现:
```cpp
#include <iostream>
using namespace std;
void insertionSort(int arr[], int n) {
for (int i = 1; i < n; i++) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
swap(arr[j], arr[j + 1]);
}
}
}
}
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 pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
void selectionSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
int min_idx = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[min_idx]) {
min_idx = j;
}
}
swap(arr[i], arr[min_idx]);
}
}
int main() {
int arr[] = {5, 3, 8, 4, 2};
int n = sizeof(arr) / sizeof(arr[0]);
// 直接插入排序
insertionSort(arr, n);
cout << "直接插入排序后的结果:";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
// 冒泡排序
bubbleSort(arr, n);
cout << "冒泡排序后的结果:";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
// 快速排序
quickSort(arr, 0, n - 1);
cout << "快速排序后的结果:";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
// 简单选择排序
selectionSort(arr, n);
cout << "简单选择排序后的结果:";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
```
以上是一组数据通过这四种排序算法进行排序的 C++ 代码实现。
阅读全文