开始设计
This commit is contained in:
@@ -0,0 +1,52 @@
|
||||
#include "c_BinarySearch.h"
|
||||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
|
||||
typedef struct {
|
||||
int id;
|
||||
char name[20];
|
||||
double score;
|
||||
} Student;
|
||||
|
||||
// 用户自定义的比较函数:按学号 (id) 升序比较
|
||||
int compareStudentsById(const void* a, const void* b) {
|
||||
const Student* s1 = (const Student*)a;
|
||||
const Student* s2 = (const Student*)b;
|
||||
|
||||
if (s1->id < s2->id) return -1;
|
||||
if (s1->id > s2->id) return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int main() {
|
||||
// 准备一个已经按 id 排好序的结构体数组
|
||||
Student students[] = {
|
||||
{101, "Alice", 92.5},
|
||||
{105, "Bob", 88.0},
|
||||
{109, "Charlie", 95.0},
|
||||
{112, "David", 79.5}
|
||||
};
|
||||
size_t count = sizeof(students) / sizeof(students[0]);
|
||||
|
||||
// 创建一个查找模板(只需要填入你想查找的依据字段)
|
||||
Student targetKey;
|
||||
targetKey.id = 109;
|
||||
|
||||
// 调用通用二分查找
|
||||
Student* result = (Student*)c_BinarySearch(
|
||||
&targetKey, // 目标元素的指针
|
||||
students, // 数组首地址
|
||||
count, // 元素数量
|
||||
sizeof(Student), // 每个结构体占用的字节大小
|
||||
compareStudentsById // 比较函数的指针
|
||||
);
|
||||
|
||||
// 检查并输出结果
|
||||
if (result != NULL) {
|
||||
printf("成功找到!姓名: %s, 成绩: %.1f\n", result->name, result->score);
|
||||
} else {
|
||||
printf("未找到学号为 %d 的学生。\n", targetKey.id);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user