#include "stdio.h"
typedef struct student{
int id; /*学生编号*/
char name[10]; /*学生姓名*/
float score; /*成绩*/
}Student;
int search(Student stu[],int n,int key){
int i;
for(i=0; i<n; i++)
if( stu[i].id == key ) /*查找成功*/
return i;
return -1; /*查找失败*/
}
void main()
{
Student stu[4] = {{1004,"TOM",100} ,
{1002,"LILY",95},
{1001,"ANN",93},
{1003,"LUCY",98}
}; /*初始化结构体数组*/
int addr; /*要查找的记录的地址*/
addr = search(stu,4,1003);
printf("Student ID: %d\n",stu[addr].id); /*输出查找到的记录的信息*/
printf("Student name: %s\n",stu[addr].name);
printf("Student score: %f\n",stu[addr].score);
}
#include "stdio.h"
bin_search(int A[],int n,int key){
int low,high,mid;
low = 0;
high = n-1;//因为从0开始,所以减1
while(low<=high)
{
mid = (low + high)/2;//从中间开始找,先找出中间的数为多少
if(A[mid]==key)return mid; /*查找成功,返回mid*/
if(A[mid]<key){
low = mid + 1; /*在后半序列中查找*/
}
if(A[mid]>key){
high = mid - 1; /*在前半序列中查找*/
}
}
return -1; /*查找失败,返回-1*/
}
main()
{
int A[10] = {2,3,5,7,8,10,12,15,19,21},i,n ,addr;
printf("The contents of the Array A[10] are\n");
for(i=0;i<10;i++)
printf("%d ",A[i]); /*显示数组A中的内容*/
printf("\nPlease input a interger for search\n");
scanf("%d",&n); /*输入待查找的元素*/
addr = bin_search(A,10,n); /*折半查找,返回该元素在数组中的下标*/
if(-1 != addr) /*查找成功*/
printf("%d is at the %dth unit is array A\n ",n,addr);
else printf("There is no %d in array A\n",n); /*查找失败*/
}