可以参考stl中lower_bound算法。

#include "stdafx.h"
#include <iostream>
using namespace std;
int BinSearchFirst(int arr[], int begin, int end, int target)
{
int mid = 0;
int half = 0;
int len = end - begin;
while (len > 0)
{
half = len>>1;
mid = begin + half;
if (arr[mid] < target)
{
begin = mid + 1;
len = len - half - 1;
}
else
len = half;
}
return begin;
}
int main()
{
int arr[] = {4, 10, 10, 30, 40, 100};
int pos = BinSearchFirst(arr, 0, sizeof(arr) / sizeof(*arr), 10);
cout<<pos<<endl;
}
本文介绍了一种二分查找算法的实现方法,用于在一个有序数组中查找指定目标值首次出现的位置。通过不断缩小搜索范围直至找到目标或确定目标不存在,该算法能够高效地完成查找任务。
945

被折叠的 条评论
为什么被折叠?



