按字母數字序列對字串排序
給定字串的列表按字母數字順序或字典順序排序。例如,以下單詞:Apple、Book、Aim,它們將按以下順序排序:Aim、Apple、Book。如果有一些數字,則可以將它們放在字母字串之前。
輸入和輸出
Input: A list of strings: Ball Apple Data Area 517 April Man 506 Output: Strings after sort: 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 << "Strings before sort:"<< endl;
display(N, str);
sortStr(N, str);
cout << "Strings after sort:"<<endl;
display(N, str);
}輸出
Strings before sort: Ball Apple Data Area 517 April Man 506 Strings after sort: 506 517 Apple April Area Ball Data Man
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP