在整型有序陣列中查詢想要的數字, 找到了返回下標,找不到返回-1.(折半查詢)
阿新 • • 發佈:2018-12-12
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
int BinarySearch(int a[], int key, int len)
{
int ret = -1;//找到了返回下標,找不到返回-1.
int left = 0;
int right = len - 1;
while (left <= right)
{
int mid = (left + right) / 2;
if (a[mid] > key)
{
right = mid - 1;
}
else if (a[mid] < key)
{
left = mid + 1;
}
else
{
ret = mid;
break;
}
}
return ret;
}
int main()
{
int a[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int size = sizeof(a) / sizeof(a[0]);
int key;
scanf("%d", &key);
int ret = BinarySearch(a, key, size);
if (ret != - 1)
{
printf("找到了,下標為%d\n", ret);
}
else
{
printf("沒找到\n");
}
system("pause");
return 0;
}