C++写一个函数,用起泡法对输入的10个字符串按从小到大顺序排列
时间: 2024-02-28 20:55:44 浏览: 25
好的,这里是一个用起泡法对输入的10个字符串按从小到大顺序排列的C++函数示例:
```c++
#include <iostream>
#include <string>
using namespace std;
void bubble_sort_strings(string str_list[], int n) {
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i-1; j++) {
if (str_list[j] > str_list[j+1]) {
swap(str_list[j], str_list[j+1]);
}
}
}
}
int main() {
string str_list[10] = {"apple", "banana", "orange", "pear", "grape", "kiwi", "watermelon", "mango", "pineapple", "peach"};
int n = 10;
bubble_sort_strings(str_list, n);
for (int i = 0; i < n; i++) {
cout << str_list[i] << " ";
}
cout << endl;
return 0;
}
```
这个函数接收一个包含10个字符串的数组和数组的大小作为输入,并使用嵌套的循环来进行起泡排序。在内部循环中,我们比较相邻的两个字符串,如果它们的顺序不正确,就交换它们。最终,我们输出已排序的字符串数组。
请注意,这个函数是对字符串进行排序的,而不是对数字进行排序。如果你需要对数字进行排序,需要先将数字转换为字符串。