关于#c++#的问题:【问题描述】写一个函数,用冒泡法对输入的10个字符按由大到小顺序排列

【问题描述】
写一个函数,用冒泡法对输入的10个字符按由大到小顺序排列。需要编程过程。


#include <iostream>
using namespace std;
void BSort(char a[],int n)
{
    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < n - i - 1; j++) {
            if (a[j] < a[j + 1]) {
                char t = a[j];
                a[j] = a[j + 1];
                a[j + 1] = t;
            }
        }
    }
}
int main() {
    char a[10] = {0};
    cout<<"请输入10个字符:"<<endl;
    for (int i = 0; i < 10; i++) {
       cin >> a[i] ;
    }
    BSort(a,10);
    for (int i = 0; i < 10; i++)
        cout<< a[i]<<" ";
    return 0;
}

下面是一个示例,说明如何在 C++ 中实现一个函数,该函数使用冒泡排序算法按降序对 10 个字符的数组进行排序:

#include <iostream>

// function to sort an array of 10 characters in descending order using the bubble sort algorithm
void bubbleSortDescending(char arr[]) {
  // iterate through the array
  for (int i = 0; i < 10; i++) {
    // iterate through the array again, comparing each element to the one after it
    for (int j = 0; j < 9-i; j++) {
      // if the current element is less than the one after it, swap them
      if (arr[j] < arr[j+1]) {
        char temp = arr[j];
        arr[j] = arr[j+1];
        arr[j+1] = temp;
      }
    }
  }
}

int main() {
  // initialize an array of characters
  char arr[] = {'d', 'c', 'b', 'a', 'f', 'e', 'h', 'g', 'j', 'i'};
  
  // sort the array in descending order
  bubbleSortDescending(arr);
  
  // print the sorted array
  for (int i = 0; i < 10; i++) {
    std::cout << arr[i] << " ";
  }
  
  return 0;
}

该程序将输出以下内容:

j i h g f e d c b a 


您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632