3.18二分搜索算法各种变种

编程之美3.18后面的二分查找题解:

#include<stdlib.h>
#include<stdio.h>
//最大索引,等于k
int bisearch(int* arr, int b, int e, int v)
{
	int minIndex = b, maxIndex = e, midIndex = 0;
	while (minIndex < maxIndex - 1)
	{
		midIndex = minIndex + ((maxIndex - minIndex) >> 1);
		if (arr[midIndex] <= v) minIndex = midIndex;
		else maxIndex = midIndex - 1;
	}
	if (arr[maxIndex] == v) return maxIndex;
	else if (arr[minIndex] == v) return minIndex;
	else return -1; 
}
//任意一个等于V的索引
int bisearch2(int* arr, int b, int e, int v)
{
	int minIndex = b, maxIndex = e, midIndex = 0;
	while (minIndex <= maxIndex)
	{
		midIndex = minIndex + ((maxIndex - minIndex) >> 1);
		if (arr[midIndex] == v) return midIndex;
		else if (arr[midIndex] < v) minIndex = midIndex + 1;
		else maxIndex = midIndex - 1;
	}
	return -1;
}
//最小索引,等于k
int bisearch3(int* arr, int b, int e, int v)
{
	int minIndex = b, maxIndex = e, midIndex = 0;
	while (minIndex < maxIndex - 1)
	{
		midIndex = minIndex + ((maxIndex - minIndex) >> 1);
		if (arr[midIndex] >= v) maxIndex = midIndex;
		else minIndex = midIndex + 1;
	}
	if (arr[minIndex] == v) return minIndex;
	else if (arr[maxIndex] == v) return maxIndex;
	return -1;
}
//最小的索引,大于k
int bisearch4(int* arr, int b, int e, int v)
{
	int minIndex = b, maxIndex = e, midIndex = 0;
	while (minIndex <= maxIndex - 1)
	{
		midIndex = minIndex + ((maxIndex - minIndex) >> 1);
		if (arr[midIndex] > v) maxIndex = midIndex;
		else minIndex = midIndex + 1;
	}
	if (arr[maxIndex] > v) return maxIndex;
	return -1;
}
//最大的索引,小于k
int bisearch5(int* arr, int b, int e, int v)
{
	int minIndex = b, maxIndex = e, midIndex = 0;
	while (minIndex < maxIndex - 1)
	{
		midIndex = minIndex + ((maxIndex - minIndex) >> 1);
		if (arr[midIndex] >= v) maxIndex = midIndex - 1;
		else minIndex = midIndex;
	}
	if (arr[maxIndex] < v) return maxIndex;
	if (arr[minIndex] < v) return minIndex;
	return -1;
}
int main()
{
	int arr[] = {1,2,3,4,5,5,5,6,6,7,8,9,9};
	int k;
	while(1)
	{
		scanf("%d",&k);
		printf("%d,%d\n",sizeof(arr)/sizeof(arr[0]),bisearch5(arr, 0, sizeof(arr)/sizeof(arr[0]) - 1,k));
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值