按字母数字顺序对字符串进行排序
给定字符串的列表按字母数字顺序或字典顺序排序。就像这些单词一样:Apple,Book,Aim,它们将被排序为Aim,Apple,Book,如果有一些数字,可以将它们放在字母字符串的前面。
输入输出
Input: A list of strings: Ball Apple Data Area 517 April Man 506 Output: 排序后的字符串: 506 517 Apple April Area Ball Data Man
算法
sortStr(strArr, n)
输入: 所有字符串的列表,元素数。
输出-字符串按字母数字排序。
Begin
for round := 1 to n-1, do
for i := 0 to n-round, do
res := compare str[i] and str[i+1] //either +ve, or –ve or 0
if res > 0, then
swap str[i] and str[i+1]
done
done
End示例
#include<iostream>
#define N 8
using namespace std;
void display(int n, string str[]) {
for(int i = 0; i<n; i++)
cout << str[i] << " "; //print the string from array
cout << endl;
}
void sortStr(int n, string str[]) {
int i, round, res;
for(round = 1; round<n; round++)
for(i = 0; i<n-round; i++) {
res = str[i].compare(str[i+1]);
if(res > 0)
swap(str[i], str[i+1]);//swap strings
}
}
main() {
string str[N] = {"Ball", "Apple", "Data", "Area", "517", "April", "Man", "506"};
cout << "排序前的字符串:"<< endl;
display(N, str);
sortStr(N, str);
cout << "排序后的字符串:"<<endl;
display(N, str);
}输出结果
排序前的字符串: Ball Apple Data Area 517 April Man 506 排序后的字符串: 506 517 Apple April Area Ball Data Man
热门推荐
10 香港老妈结婚祝福语简短
11 毕业立体贺卡祝福语简短
12 简短新年年会祝福语
13 评论小品祝福语大全简短
14 恭喜师兄结婚祝福语简短
15 员工集体辞职祝福语简短
16 高中新生祝福语 简短
17 装修祝福语男生搞笑简短
18 生日开业蛋糕祝福语简短