//
// main.c
// BinarySearch
//
// Created by steve xiaohu zhao on 2023/10/16.
//
#include <stdio.h>
// 二分法查找指定元素在数组中出现的索引位置
int BinarySearch(int *array, int length, int k) {
int left, right, mid, NotFound = -1;
// 设置左端点起点
left = 0;
// 设置右端点起点
right = length;
while (left < right) {
// 计算中间元素坐标
mid = (left + right) / 2;
if (k < array[mid]) {
// 调整有边界
right = mid +1;
} else if (k > array[mid]) {
// 调整左边界
left = mid + 1;
} else {
// 查找成功, 返回数据元素的下标
return mid;
}
}
// 循环结束如果没有找到对应的元素, 则返回 not found
return NotFound;
}
int main(int argc, const char * argv[]) {
int nums[100];
// 0, 5, 10, 15, 20, 25, ...., 99*5 = 495
for (int i = 0; i < 100; i++) {
nums[i] = i * 5;
printf("%d 的索引位置是:%d \n", i*5, i);
}
printf("====================================\n");
int idx = BinarySearch(nums, 100, 20);
printf("找到啦~~~索引值是:%d \n", idx);
return 0;
}
标签:right,int,mid,C语言,二分法,printf,left
From: https://www.cnblogs.com/zxhoo/p/17770014.html