KY2 成绩排序C

发布时间 2024-01-08 16:02:34作者: 神奇的萝卜丝

创建一个结构体,然后按要求快排就行了。

#include <stdio.h>
#include <stdlib.h>
typedef struct node{
    int num;
    char S[100];
    int score;
}student;

int divide1(student* A,int head ,int tail){//升序
    if (head==tail) return head;
    int t =A[head].score;
    student tem =A[head];
    while(head < tail){
        while(head < tail && A[tail].score > t) tail--;
        if(head!=tail) A[head++]=A[tail];
        while(head < tail && A[head].score < t ) head++;
        if(head != tail) A[tail--]=A[head];
    }
    A[head]=tem;
    return head;
}
int divide2(student* A,int head ,int tail){//名次排名
    if (head==tail) return head;
    int t =A[head].num;
    student tem =A[head];
    while(head < tail){
        while(head < tail && A[tail].num > t) tail--;
        if(head!=tail) A[head++]=A[tail];
        while(head < tail && A[head].num < t ) head++;
        if(head != tail) A[tail--]=A[head];
    }
    A[head]=tem;
    return head;
}
int divide3(student* A,int head ,int tail){//降序
    if (head==tail) return head;
    int t =A[head].score;
    student tem =A[head];
    while(head < tail){
        while(head < tail && A[tail].score < t) tail--;
        if(head!=tail) A[head++]=A[tail];
        while(head < tail && A[head].score > t ) head++;
        if(head != tail) A[tail--]=A[head];
    }
    A[head]=tem;
    return head;
}

void quicksort(student* A,int head, int tail ,int tag){//tag=0降序,1升序
    if(head >= tail) return;
    int x;
    if(tag==0){
        x= divide3(A,head,tail);
    }else if(tag==1){
        x= divide1(A,head,tail);
    }else{
        x= divide2(A,head,tail);
    }
    if(x>head) quicksort(A,head,x-1,tag);
    if(x<tail) quicksort(A,x+1,tail,tag);
}

int main(){
    int n , flag;
    while(scanf("%d %d",&n,&flag) != EOF){
        student* A=(student*) malloc(sizeof(student)*n);
        for(int i = 0 ; i < n ; i++){
            A[i].num=i;
            scanf("%s %d",A[i].S,&A[i].score );
        }
        quicksort(A,0,n-1,flag);
        int head = 0 ;
        while(head<n-1){
            int t = head + 1;
            while(A[head].score == A[t].score && t < n){
                t++;
            }
            if(t!=head+1) quicksort(A,head,t-1,-1);
            head=t;
        }
            for(int i = 0 ; i < n ; i++){
                printf("%s %d\n",A[i].S,A[i].score);
            }
    }
    return 0;
}

结果如下