二分查找递归实现,非递归实现

二分查找非递归实现
一  区间左闭右闭

#include<stdio.h>
#include<stdlib.h>
int BinarySerach(int *arr, int x, int sz)
{
	int left = 0;
	int right = sz - 1;//左闭右闭
	
	while (left <= right)//注意有等号
	{
		int mid = left + (right - left) / 2;
		while(arr[mid] == x)
		{
			return mid;
		}
		if (arr[mid]>x)
		{
			right = mid - 1;//注意是mid-1
		}
		
		if (arr[mid]<x)
		{
			left = mid + 1;
		}
	}
	return -1;

}
int main()
{
	
 	        int arr[10] = { 1, 3, 5, 6, 7, 9, 11, 12, 14, 48 };
	        int sz = sizeof(arr) / sizeof(arr[0]);
			int ret=BinarySerach(arr, 50, sz);
			printf("%d\n", ret);
			system("pause");
			return 0;
		
}


二  区间左闭右开
#include<stdio.h>
#include<stdlib.h>
int BinarySerach(int *arr, int x, int sz)
{
	int left = 0;
	int right = sz;//左闭右开
	while (left < right)//注意此处没有等于
	{
		int mid = left + (right - left) / 2;
		if (arr[mid] == x)
		{
			return mid;
		}
	
	if (arr[mid]>x)
	{
		right = mid ;//注意此处不是mid-1
	}

	if (arr[mid]<x)
	{
		left = mid + 1;
	}
}
return -1;

}

int main()
{
	int arr[10] = { 1, 3, 5, 6, 7, 9, 11, 12, 14, 48 };
	int sz = sizeof(arr) / sizeof(arr[0]);
	int ret = BinarySerach(arr, 9, sz);
	printf("%d\n", ret);
	system("pause");
	return 0;
}
二分查找递归实现
#include<stdio.h>
#include<stdlib.h>
int BinarySerachR(int *arr, int x, int left, int right)
{
	while (left <= right)

	{
		int mid = (right - left) / 2 + left;
		if (arr[mid] == x)
			return mid;
		if (arr[mid] > x)
		{
			return BinarySerachR(arr, x, left, mid - 1);
		}
		else
		{
			return BinarySerachR(arr, x, mid + 1, right);
		}
	}
	return -1;
}
int main()
{
	int arr[10] = { 1, 3, 5, 6, 7, 9, 11, 12, 14, 48 };
	int sz = sizeof(arr) / sizeof(arr[0]);
	int ret=BinarySerachR(arr, 50, 0, sz);
	printf("%d\n", ret);
	system("pause");
	return 0;
	
}


©️2020 CSDN 皮肤主题: 技术工厂 设计师:CSDN官方博客 返回首页