实验原理
查找又称为检索,就是根据给定的某一个值从一个数据元素集合中找出某个特定的数据 元素。查找和排序一样,是数据处理中经常使用的运算,查找算法的优劣对整个软件系统的 影响很大。在一个数据元素集合中进行查找可选用的方法和该数据元素集合的存储结构有很 大关系。查找有内查找和外查找之分。对于线性表,主要的内查找算法有顺序查找、二分查 找等。但要注意,二分查找只适合于有序的线性表。
#include <stdio.h>
#include "stdlib.h"
#define N 12
struct StudentInfo {
char ID[10];
char *name;
float score;
} StuInfo[N] =
{
{"0800301105", "JACK", 95},
{"0800201505", "LUN", 85},
{"0400820115", "MARY", 75.5},
{"0400850122", "KATE", 78.9},
{"0500201011", "LILI", 88},
{"0800401105", "JACK", 96},
{"0600830105", "JAN", 98.4},
{"0952520012", "SAM", 75},
{"9721000045", "OSCAR", 64},
{"0700301105", "JACK", 97},
{"0458003312", "ZOE", 68.9},
{"0400830211", "BOBI", 87.6}
};
void sortStudentID() {
struct StudentInfo temp;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N - 1 - i; j++) {
if (atoi(StuInfo[j + 1].ID) < atoi(StuInfo[j].ID)) {
temp = StuInfo[j];
StuInfo[j] = StuInfo[j + 1];
StuInfo[j + 1] = temp;
}
}
}
}
void sortStudentScore() {
struct StudentInfo temp;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N - 1 - i; j++) {
if (StuInfo[j + 1].score > StuInfo[j].score) {
temp = StuInfo[j];
StuInfo[j] = StuInfo[j + 1];
StuInfo[j + 1] = temp;
}
}
}
}
int Search_Bin_ID(int ID) {
int low = 0;
int high = 12;
int mid = 1;
while (low <= N && mid > 0) {
mid = low + (high - low) / 2;
if (ID == atoi(StuInfo[mid].ID)) {
printf("查找到的结果为:%s\t%s\t%f\n", StuInfo[mid].ID, StuInfo[mid].name, StuInfo[mid].score);
return 1;
}
if (ID < atoi(StuInfo[mid].ID))
high = mid - 1;
else
low = mid + 1;
}
printf("未查到该学号");
return 0;
}
int Search_Bin_Score(float score) {
int low = 0;
int high = 12;
int mid = 1;
while (low <= N && mid > 0) {
mid = low + (high - low) / 2;
if (score == StuInfo[mid].score) {
printf("查找到的结果为:%s\t%s\t%f\n", StuInfo[mid].ID, StuInfo[mid].name, StuInfo[mid].score);
return 1;
}
if (score > StuInfo[mid].score)
high = mid - 1;
else
low = mid + 1;
}
printf("未查到该成绩!");
return 0;
}
int main() {
int ID;
float score;
printf("按照学号(ID)递增排序:\n");
sortStudentID();
for (int i = 0; i < N; i++) {
printf("%s\t%s\t%f\n", StuInfo[i].ID, StuInfo[i].name, StuInfo[i].score);
}
printf("请输入要查找的学号:\n");
scanf("%d", &ID);
Search_Bin_ID(ID);
printf("\n\n");
printf("按照成绩(score)递减排序:\n");
sortStudentScore();
for (int i = 0; i < N; i++) {
printf("%s\t%s\t%f\n", StuInfo[i].ID, StuInfo[i].name, StuInfo[i].score);
}
printf("请输入要查找的成绩:\n");
scanf("%f", &score);
Search_Bin_Score(score);
}