本帖最後由 鄭繼威 於 2023-4-15 14:18 編輯
假設班上有五位同學, 其成績資料如下:
string name[5]={"大雄","小叮噹","宜靜","技安","阿福"};
int score[5]={60,80,100,40,75};
試利用選擇排序法, 為成績表加上排名.
由大到小,換成績的時候順便換名字
- #include<iostream>
- #include<cstdlib>
- using namespace std;
- int main()
- {
- string tmp1;
- int tmp2;
- string name[5]={"大雄","小叮噹","宜靜","技安","阿福"};
- int score[5]={60,80,100,40,75};
- cout<<"原始資料"<<endl;
- cout<<"-------------"<<endl;
- cout<<"姓名\t成績"<<endl;
- cout<<"-------------"<<endl;
複製代碼- for(int i=0; i<=4; i++)
- cout<<name[i]<<"\t"<<score[i]<<endl;
- cout<<endl;
- //開始排序
- for(int i=0; i<=3; i++)
- {
- for(int j=i+1; j<=4; j++)
- {
- //倆倆(i,j)比較
- //右邊大於左邊就交換->換到最後最左邊會最大
- if(score[j]>score[i])
- {
- tmp1=name[j];
- name[j]=name[i];
- name[i]=tmp1;
- tmp2=score[j];
- score[j]=score[i];
- score[i]=tmp2;
- }
- }
- }
複製代碼- cout<<"依成績排序後資料"<<endl;
- cout<<"---------------------"<<endl;
- cout<<"姓名\t成績\t排名"<<endl;
- cout<<"---------------------"<<endl;
- for(int i=0; i<=4; i++)
- cout<<name[i]<<"\t"<<score[i]<<"\t"<<i+1<<endl;
- cout<<endl;
- system("pause");
- return 0;
- }
複製代碼 |