【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);
}
}
上一篇: 洛谷p2055:假期宿舍(二分图)
下一篇: 进制转化