C++ 冒泡排序算法:查找数组极值并排序
C++ 冒泡排序算法:查找数组极值并排序
本代码使用 C++ 实现冒泡排序算法,可以根据指定的方向(正向或反向)和极值类型(最大值或最小值)在整形数组中查找极值,并展示排序过程。
#include <iostream>
using namespace std;
// 冒泡排序函数
void bubbleSort(int arr[], int n, int direction, int extremeType) {
int temp;
// 循环 n-1 次
for (int i = 0; i < n - 1; i++) {
// 循环比较相邻元素
for (int j = 0; j < n - i - 1; j++) {
// 根据方向和极值类型判断是否交换
if ((direction == 1 && extremeType == 1 && arr[j] > arr[j + 1]) ||
(direction == 1 && extremeType == 2 && arr[j] < arr[j + 1]) ||
(direction == 2 && extremeType == 1 && arr[j] < arr[j + 1]) ||
(direction == 2 && extremeType == 2 && arr[j] > arr[j + 1])) {
// 交换元素
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
// 打印排序过程
cout << "排序过程:";
for (int k = 0; k < n; k++) {
cout << arr[k] << " ";
}
cout << endl;
}
}
int main() {
int arr[20];
int n;
int direction, extremeType;
// 输入数组大小
cout << "请输入数组大小 (n <= 20): ";
cin >> n;
// 输入数组元素
cout << "请输入数组元素:\n";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
// 输入冒泡方向
cout << "请输入冒泡方向 (1-正向/2-反向): ";
cin >> direction;
// 输入极值类型
cout << "请输入极值类型 (1-最大值/2-最小值): ";
cin >> extremeType;
// 调用冒泡排序函数
bubbleSort(arr, n, direction, extremeType);
// 打印排序后的数组
cout << "排序后的数组:";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
代码说明:
bubbleSort()函数接收数组、数组大小、冒泡方向和极值类型作为参数。- 循环 n-1 次,每次循环比较相邻元素并根据方向和极值类型进行交换。
- 在每次循环中打印排序过程。
main()函数输入数组大小、数组元素、冒泡方向和极值类型,并调用bubbleSort()函数进行排序。- 最后打印排序后的数组。
注意:
- 该代码使用 C++ 语言编写。
- 数组大小需要小于等于 20。
- 冒泡方向和极值类型分别由 1 和 2 表示。
- 代码中包含注释,解释了代码的功能。
原文地址: https://www.cveoy.top/t/topic/nWq3 著作权归作者所有。请勿转载和采集!