주어진 문자열 목록은 영숫자 순서 또는 사전 순서로 정렬됩니다. 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