在排序的数组中二分查找一个元素,返回在数组中它第一次出现的位置

可以参考stl中lower_bound算法。

 

 

#include "stdafx.h"
#include 
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<


 

你可能感兴趣的:(算法与数据结构,算法)