元二分搜索(Steven Skiena 在《算法设计手册》第 134 页中也称为单边二分搜索)是二分搜索的一种修改形式,它以增量方式构建数组中目标值的索引。与普通二分搜索一样,元二分搜索需要 O(log n) 时间。
元二分搜索,也称为单边二分搜索,是二分搜索算法的一种变体,用于搜索有序列表或元素数组。该算法旨在减少在列表中搜索给定元素所需的比较次数。
元二分搜索背后的基本思想是从包含整个数组的大小为 n 的初始区间开始。然后,该算法像二分搜索一样计算中间元素,并将其与目标元素进行比较。如果找到目标元素,则搜索终止。如果中间元素大于目标元素,则算法将新区间设置为前一个区间的左半部分,如果中间元素小于目标元素,则将新区间设置为前一个区间的右半部分间隔。但是,与二分搜索不同,元二分搜索不会对循环的每次迭代执行比较。
相反,该算法使用启发式方法来确定下一个间隔的大小。它计算中间元素的值与目标元素的值之间的差值,并将差值除以预定常数(通常为2)。然后将该结果用作新区间的大小。该算法将继续进行,直到找到目标元素或确定它不在列表中。
元二分搜索相对于二分搜索的优势在于,它在某些情况下可以执行更少的比较,特别是当目标元素接近列表开头时。缺点是在其他情况下,该算法可能比二分查找执行更多的比较,特别是当目标元素接近列表末尾时。因此,当列表的排序方式与目标元素的分布一致时,元二分搜索是最有效的。
这是元二分搜索的伪代码:
function meta_binary_search(A, target):
n = length(A)
interval_size = n
while interval_size > 0:
index = min(n - 1, interval_size / 2)
mid = A[index]
if mid == target:
return index
elif mid < target:
interval_size = (n - index) / 2
else:
interval_size = index / 2
return -1
例子:
Input: [-10, -5, 4, 6, 8, 10, 11], key_to_search = 10
Output: 5
Input: [-2, 10, 100, 250, 32315], key_to_search = -2
Output: 0
确切的实现有所不同,但基本算法有两个部分:
1、计算出存储最大数组索引需要多少位。
2、通过确定索引中的每个位应设置为 1 还是 0,增量构造数组中目标值的索引。
方法:
1、在变量 lg 中存储表示最大数组索引的位数。
2、使用 lg 在 for 循环中开始搜索。
3、如果找到该元素,则返回 pos。
4、否则,在 for 循环中增量构造索引以达到目标值。
5、如果找到元素,则返回 pos,否则返回 -1。
下面是上述方法的实现:
//C# implementation of above approach
using System;
using System.Collections.Generic;
class GFG
{
// Function to show the working of Meta binary search
static int bsearch(List<int> A, int key_to_search)
{
int n = (int) A.Count;
//int lg = 0;
// Set number of bits to represent largest array index
int lg = (int)Math.Log(n-1, 2.0) + 1;
// This is redundant and will cause error
//while ((1 << lg) < n - 1)
//{
// lg += 1;
//}
int pos = 0;
for (int i = lg - 1; i >= 0; i--)
{
if (A[pos] == key_to_search)
{
return pos;
}
// Incrementally construct the
// index of the target value
int new_pos = pos | (1 << i);
// find the element in one
// direction and update position
if ((new_pos < n) && (A[new_pos] <= key_to_search))
{
pos = new_pos;
}
}
// if element found return pos otherwise -1
return ((A[pos] == key_to_search) ? pos : -1);
}
// Driver code
static public void Main()
{
List<int> A = new List<int>();
int[] arr = {-2, 10, 100, 250, 32315};
for (int i = 0; i < arr.Length; i++)
{
A.Add(arr[i]);
}
Console.WriteLine(bsearch(A, 10));
}
}
// This code is contributed by Rajput-Ji
// This implementation was improved by Tanin
输出:
1
时间复杂度: O(log n),其中 n 是给定数组的大小
辅助空间: O(1) ,因为我们没有使用任何额外空间
元二分搜索算法详解:原理、优势与C#实现,
本文介绍了元二分搜索,一种针对有序列表的搜索算法,它通过增量构建目标值索引,相比普通二分搜索,在目标元素接近列表开头时能减少比较次数。文章提供了C#实现示例,并讨论了其时间复杂度和空间复杂度。
&spm=1001.2101.3001.5002&articleId=136670710&d=1&t=3&u=8e0669e2f5b24f8288ba0c8968abe754)

被折叠的 条评论
为什么被折叠?



