#include using namespace std;

void bubbleSort(int arr[], int n, int direction, int type) { for (int i = 0; i < n - 1; i++) { for (int j = 0; j < n - i - 1; j++) { if (direction == 1) { if (type == 1) { // 从小到大 if (arr[j] > arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } else { // 从大到小 if (arr[j] < arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } else { if (type == 1) { // 从小到大 if (arr[j] < arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } else { // 从大到小 if (arr[j] > arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } } } }

int main() { int n; cout << "请输入需要排序的元素个数(n<=20):"; cin >> n;

int arr[n];
cout << "请输入需要排序的元素:";
for (int i = 0; i < n; i++) {
    cin >> arr[i];
}

cout << "请选择排序规则(1为从小到大,2为从大到小):";
int type;
cin >> type;

cout << "请选择冒泡方向(1为正向,2为反向):";
int direction;
cin >> direction;

bubbleSort(arr, n, direction, type);

cout << "排序后的结果为:";
for (int i = 0; i < n; i++) {
    cout << arr[i] << " ";
}

return 0;

}

C++ 冒泡排序算法:实现正向和反向排序以及最大值和最小值查找

原文地址: https://www.cveoy.top/t/topic/nWra 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录