使用選擇法進行排序,代碼:ios
#include<iostream> using namespace std; struct Students { int num; char name[20]; char sex; int score; }; int main() { struct Students su[5] ={ {1001,"xway",'M',93},{1002,"minve",'F',49},{1003,"glove",'F',43}, {1004,"sk",'M',65},{1005,"fys",'M',86} }; struct Students temp; const int n=5; int i,j,k; cout<<"before sort:"<<endl; for(i=0;i<n;i++) printf("%4d %8s %c %3d\n",su[i].num,su[i].name,su[i].sex,su[i].score); cout<<"sortted:"<<endl; for(i=0;i<n-1;i++){ k=i;//初始化最大值下標爲當前起始位置 for(j=i+1;j<n;j++) if(su[j].score>su[k].score)//遍歷並找到這次的最大值 k=i;//mark下標 temp=su[k];su[k]=su[i];su[i]=temp;//交換,吧=把這次的最大值放到當前位置 } for(i=0;i<n;i++) printf("%4d %8s %c %3d\n",su[i].num,su[i].name,su[i].sex,su[i].score); system("pause"); return 0; }
運行結果spa