返回列表 發帖

排序 (四)

本帖最後由 李泳霖 於 2022-8-12 19:19 編輯

假設班上有五位同學, 其成績資料如下:
string name[5]={"大雄","小叮噹","宜靜","技安","阿福"};
int score[5]={60,80,100,40,75};


試利用選擇排序法, 為成績表加上排名.

  1. #include<iostream>   
  2. #include<cstdlib>   
  3. using namespace std;  
  4. int main()    //主函式
  5. {
  6.     string name[5]={"大雄","小叮噹","宜靜","技安","阿福"};
  7.     int score[5]={60,80,100,40,75};
  8.     int tmp;
  9.     cout<<"原始資料"<<endl;
  10.     cout<<"-------------"<<endl;
  11.     cout<<"姓名\t成績"<<endl;
  12.     cout<<"-------------"<<endl;
  13.     for(int i=0;i<=4;i++)
  14.     {
  15.             cout<<name[i]<<"\t"<<score[i]<<endl;
  16.     }         
  17.             for(int i=0;i<4;i++)
  18.             {
  19.                     for(int j=i+1;j<5;j++)
  20.                     {
  21.                             if(score[i]<score[j])
  22.                             {
  23.                                  tmp=score[i];
  24.                                  score[i]=score[j];
  25.                                  score[j]=tmp;
  26.                             }
  27.                     }
  28.             }      
  29.    
  30.    
  31.    
  32.    
  33.    
  34.    
  35.      cout<<endl<<"依成績排序後資料"<<endl;
  36.      cout<<"-------------"<<endl;
  37.      cout<<"姓名\t成績\t排名"<<endl;
  38.       for(int i=0;i<=4;i++)
  39.     {
  40.             cout<<name[i]<<"\t"<<score[i]<<"\t"<<i+1<<endl;
  41.     }
  42.    
  43.            
  44.     system("pause");      
  45.     return 0;              
  46. }
複製代碼

此帖僅作者可見

TOP

返回列表