โจทย์
การเรียงลำดับขึ้นหรือลง สามารถทำได้โดยใช้ string sort method และวิธีอื่นๆ ใน C++ แต่ที่นี่ ใช้ string compare (เปรียบเทียบคำแรกกับคำที่สอง) และ copy (คัดลอกคำแรกในตัวแปร temp) method ที่เกี่ยวข้องในลูปในและลูปนอก เพื่อวางคำในลำดับถอยหลัง ดังนี้
ตัวอย่างโค้ด C++
#include<bits/stdc++.h>
using namespace std;
int main(){
char str[3][20]={"Ajay","Ramesh","Mahesh"};
char t[20];
int i, j;
for(i=1; i<3; i++){
for(j=1; j<3; j++){
if(strcmp(str[j-1], str[j])>0){
strcpy(t, str[j-1]);
strcpy(str[j-1], str[j]);
strcpy(str[j], t);
}
}
}
cout<<"Sorted in Descending Order ::";
for(i=3; i>=0; i--){
cout<<" ";
cout<<str[i]<<"\n";
}
return 0;
}
ผลลัพธ์
โปรแกรมนี้ให้ผลลัพธ์โดยการเรียงสตริงในลำดับถอยหลังหลังจากรับคำ 3 คำ (Ajay, Ramesh, และ Mahesh) เป็นอินพุต ดังนี้
Sorted in Descending Order:: Ramesh Mahesh Ajay