C语言二分查找爱吃窝窝头2023-11-302023-11-30//2022.12.2二分查找#include<stdio.h>#include<stdlib.h>#define N 20typedef struct sqlist{ int *elem; int length; int listsize; }sql;sql L;void InitList(){ L.elem=(int *)malloc(N*sizeof(int)); if(!L.elem) exit(0); L.listsize=N; L.length=0; }void input(int n){ int i; printf("请输入值:"); for(i=1;i<=n;i++) scanf("%d",&L.elem[i]); L.length=n;}void output(){ int i; for(i=1;i<=L.length;i++) printf("%d ",L.elem[i]); printf("\n");}int x=0; int binsearch(int key){ int low,high,mid; low=1; high=L.length; while (low<=high) { x++; mid=(low+high)/2; if (key<L.elem[mid]) high=mid-1; else if (key==L.elem[mid]) return mid; else low=mid+1; } return 0;}int main(){ int n,key; InitList(); printf("请输入个数:"); scanf("%d",&n); input(n); output(); printf("请输入要查找的值:\n"); scanf("%d",&key); if (binsearch(key)!=0) printf("查找成功,在:%d的位置",binsearch(key)); else printf("查找失败!"); printf("%d",x); return 0;}