欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【C语言】二分查找

程序员文章站 2024-03-17 15:13:46
...

非递归

//二分查找
typedef int ssize_t;
typedef unsigned int size_t;
//二分查找
typedef int ssize_t;
typedef unsigned int size_t;
//非递归
ssize_t BinarySearch(int array[], size_t size, int data)
{
	size_t left, right;
	left = 0;
	right = size;
	while (left < right)
	{
		size_t mid = left + (right - left) / 2;
		if (array[mid] == data) {
			return mid;
		}
		if (data < array[mid])
		{
			right = mid;
		}
		else
		{
			left = mid+1;
		}
	}
	return -1;
}

递归

//二分查找
typedef int ssize_t;
typedef unsigned int size_t;
//递归
ssize_t BinarySearch(int array[], size_t size, int data)
{
	size_t left, right;
	left = 0;
	right = size;
	if (size <= 0)
	{
		return -1;
	}
	size_t mid = left + (right - left) / 2;
	if (data == array[mid])
	{
		return mid;
	}
	if (data < array[mid])
	{
		return BinarySearch(array, mid, data);
	}
	else
	{
		return BinarySearch(array + mid + 1, size - mid - 1, data);
	}
}