先排序后查找。
#include <stdio.h>
#include <string.h>
#define N 100
typedef struct Stu {char name[20];int score;
} STU;void Input(STU stu[], int n);
void SelectiveMethod(STU stu[], int n);
void Print(STU stu[], int n);
int BinarySearch(STU stu[], int n, STU key); //找到了返回0~n-1,找不到返回-1
int main(void) {int n;STU s[3]; //前三个人的姓名保存下来,后面查找要用STU stu[N];printf("input n:");scanf("%d", &n);if(n<3)//数据少于3直接结束 return 0;Input(stu, n); //录入数据printf("录入的信息是:\n");Print(stu, n); //打印录入的数据//保存第三位同学的姓名s[0]=stu[0];s[1]=stu[1];s[2]=stu[2];SelectiveMethod(stu, n);printf("排序后的信息是:\n");Print(stu, n); //打印排序后的数据printf("%s 姓名的同学是第%d名次\n", s[0].name, BinarySearch(stu, n, s[0])+1);printf("%s 姓名的同学是第%d名次\n", s[1].name, BinarySearch(stu, n, s[1])+1);printf("%s 姓名的同学是第%d名次\n", s[2].name, BinarySearch(stu, n, s[2])+1);return 0;
}void Input(STU stu[], int n) {for (int i = 0; i < n; i++) {printf("请输入第%d位同学的姓名与成绩,之间用空格分开:", i + 1);scanf("%s%d", stu[i].name, &stu[i].score);}return;
}void SelectiveMethod(STU stu[], int n) { //从高到低int i, j, k;STU tmp;for (i = 0; i < n - 1; i++) {k = i;for (j = i + 1; j < n; j++) {if (stu[k].score < stu[j].score)k = j;}if (k != i) {tmp = stu[k];stu[k] = stu[i];stu[i] = tmp;}}return;
}void Print(STU stu[], int n) {for (int i = 0; i < n; i++) {printf("%s\t%d\n", stu[i].name, stu[i].score);}return;
}int BinarySearch(STU stu[], int n, STU key) {int left = 0;int right = n - 1;int mid = 0;while (left <= right) {mid = (right + left) / 2;if (key.score>stu[mid].score) {right = right - 1; } else if (key.score<stu[mid].score) {left = left + 1;} else if (key.score==stu[mid].score) {//分数找到了,查一下有没有重名的情况while(mid-1>=0 && key.score==stu[mid-1].score)//将mid相同分析的最左边位置mid--;while(strcmp(key.name,stu[mid].name))mid++;return mid;}}return -1;
}