代码如下:

#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++设计一个函数使用冒泡交换的方法在一个整形数组中根据指定的冒泡方向1一正向从前向后2一反向从后向前和极值类型1一最大值2一最小值找出极值。在主函数中通过调用此函数将nn=20个无序的互不相同的整数进行排序并展示排序的过程。提示:1、函数的形式应为:void 函数名int 数组名 int 元素个数 int 冒泡方向 int 极值类型2、排序的规则从小到大或从大到小由调用函数的实际参数决定两种规

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

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