给出n个学生的考试成绩表,每条信息由姓名和分数组成,试设计一个算法:
按分数高低次序,打印出每个学生在考试中获得的名次,分数相同的为同一名次;按名次列出每个学生的姓名与分数。
要求至少使用3种以上的排序方法(必须包含快速排序算法)。
代码:
#include <bits/stdc++.h>
using namespace std;
const int MAXN=8;
typedef struct Stu{
int mark;
string name;
}Stu;
typedef struct MarkList{
Stu a[8]={{90,"Mercury"},{92,"Venus"},{41,"Earth"},{2,"Mars"},{4,"Jupiter"},{29,"Saturn"},{73,"Uranus"},{87,"Neptune"}};
public:
void disorder(){
for(int i=0;i<8;i++){
for(int j=i;j<8;j++){
if(a[i].name>a[j].name) swap(a[i],a[j]);
}
}
}
void show(){
for(int i=0;i<8;i++)
cout<<a[i].mark<<' '<<a[i].name<<endl;
cout<<"----------"<<endl;
}
void SelectionSort(){
for(int i=0;i<8;i++){
for(int j=i;j<8;j++){
if(a[i].mark<a[j].mark) swap(a[i],a[j]);
}
}
}
void MargeSort(int l,int r){
if(l==r) return ;
int mid=(l+r)/2;
MargeSort(l,mid);
MargeSort(mid+1,r);
Stu temp[r-l+1];
int pos1=l,pos2=mid+1;
for(int i=l;i<=r;i++){
if(pos1>mid){
temp[i-l]=a[pos2++];
}else if(pos2>r){
temp[i-l]=a[pos1++];
}else{
if(a[pos1].mark>a[pos2].mark)
temp[i-l]=a[pos1++];
else
temp[i-l]=a[pos2++];
}
}
for(int i=l;i<=r;i++) a[i]=temp[i-l];
}
void QuickSort(int l,int r){
if(l==r) return ;
int posl=l,posr=r;
int pi=a[l].mark;
bool flag=1;
while(posr!=posl){
while(posr!=posl&&a[posl].mark>pi){posl++;}
swap(a[posl],a[posr]);
while(posr!=posl&&a[posr].mark<=pi){posr--;}
swap(a[posl],a[posr]);
}
QuickSort(l,posl);
QuickSort(posl+1,r);
}
}MarkList;
int main()
{
MarkList a;
a.show();
a.SelectionSort();
a.show();
a.disorder();
a.show();
a.MargeSort(0,7);
a.show();
a.disorder();
a.show();
a.QuickSort(0,7);
a.show();
}