c语言二分查找(折半查找)
使用二分查找的前提条件
二分查找的基本原理
1.通过函数实现
#include<stdio.h>
int bin_search(int arr[], int left, int right, int key)//定义一个函数
{
int mid = 0;
int find = 0;
while (left <= right) {//实现折半查找
mid = left + (right - left) / 2;
if (arr[mid] > key) {
right = mid - 1;
}
else if (arr[mid] < key) {
left = mid + 1;
}
else {
find = 1;
break;
}
}
if (1 == find) {
return mid;
}
else {
return -1;
}
}
int main() {
int arr[] = { 0,1,2,3,4,5,6,7,8,9,10 };//定义一个有序数组
int key=4;
int left = 0;//左下标从0开始
int sz = sizeof(arr) / sizeof(arr[0]);//数组的大小
int right = sz - 1;//右下标数组的大小-1
scanf("%d", &key);//输入要查找的数
int result=bin_search(arr, left, right, key);//对函数进行调用
if (result!=-1) {
printf("找到了,下标为%d\n", result);
}
else {
printf("找不到\n");
}
return 0;
}
2.直接实现
#include int main() {
int arr[] = {1,2,3,4,5,6,7,8,9,10};
int left = 0;
int right = sizeof(arr)/sizeof(arr[0])-1;
int key = 7;//要找的数字
int mid = 0;//记录中间元素的下标
int find = 0;
while (left <= right) {//实现折半查找
mid = left + (right - left) / 2;
if (arr[mid] > key) {
right = mid - 1;
}
else if (arr[mid] < key) {
left = mid + 1;
}
else {
find = 1;
break;
}
}
if(1 == find )
printf("找到了,下标是%d\n", mid);
else
printf("找不到\n");
}