直接上代码
//折半查找
#include <stdio.h>
#include <stdlib.h>
#define ERROR -1
#define max 100
typedef struct{
int *data;
int length;
}arr;
void create(arr *t)
{
t->data = (int*)malloc((max)*sizeof(int));
t->length = 0;
}
void init(arr *t)
{
int tmp;
printf("输入元素,空格分隔,9999退出;\n");
for(int i = 0;;i++)
{
scanf("%d",&tmp);
if(tmp == 9999) break;
t->data[i] = tmp;
t->length ++;
}
}
void print(arr *t)
{
for(int i = 0;i < t->length;i++)
printf("%d ",t->data[i]);
}
int search(int key,arr *t)
{
int low = 0,high = t->length-1,mid;
while(low <= high)
{
mid = (low+high)/2;
if(t->data[mid] == key)
return mid;
else if(t->data[mid] < key)
low = mid+1;
else
high = mid -1;
}
return ERROR;
}
int main()
{
arr a;
create(&a);
init(&a);
// print(&a);
int key;
printf("请输入你要查找的元素:\n");
scanf("%d",&key);
int answer = search(key,&a);
if(answer == ERROR)
printf("查找失败!\n");
else
printf("查找成功!下标位于%d",answer);
return 0;
}