本帖最後由 陳品肇 於 2019-5-25 14:01 編輯
假設班上有五位同學, 其成績表格如下,
試利用氣泡排序法, 為成績表加上排名,
執行畫面如下.
- #include<iostream>
- #include<cstdlib>
- using namespace std;
- int main()
- {
- string name[5]={"大熊","小叮噹","宜靜","技安","阿福"};
- int score[5] = {60,80,100,40,75};
- int tmp;
- string tmp2;
-
- cout<<"原始資料"<<endl;
- cout<<"-----------"<<endl;
- cout<<"姓名\t成績"<<endl;
- cout<<"-----------"<<endl;
- for(int i=0;i<5;i++)
- {
- cout<<name[i]<<"\t"<<score[i]<<endl;
- }
-
-
- for(int i=0;i<4;i++)
- {
- for(int j=i+1;j<5;j++)
- {
- if(score[i]<score[j])
- {
- //成績交換
- tmp = score[i];
- score[i] = score[j];
- score[j] = tmp;
- //姓名交換
- tmp2 = name[i];
- name[i] = name[j];
- name[j] = tmp2;
- }
- }
- }
-
- cout<<endl;
- cout<<"依成績排序資料"<<endl;
- cout<<"-----------"<<endl;
- cout<<"姓名\t成績\t排名"<<endl;
- cout<<"-----------"<<endl;
- for(int i=0;i<5;i++)
- {
- cout<<name[i]<<"\t"<<score[i]<<"\t"<<i+1<<endl;
- }
-
-
- system("pause");
- return 0;
- }
複製代碼 |