Binary search is the ultimate divide-and-conquer algorithm. To find a key in a large file containing keys in sorted order, we first compare with , and depending on the result we recurse either on the first half of the file, , or on the second half, . The recurrence now is . Plugging into the master theorem (with ) we get the familiar solution: a running time of just .
Source: Algorithms by Dasgupta, Papadimitriou, Vazirani. McGraw-Hill. 2006.
Problem
The problem is to find a given set of keys in a given array.
Given: Two positive integers and , a sorted array of integers from to and a list of integers .
Return: For each , output an index s.t. or "-1" if there is no such index.
二进制搜索是最终的分而治之 算法。要找到一把钥匙在包含密钥的大文件的排序顺序,我们首先比较同,并根据结果,我们要么调用那些文件的前半部分,或在下半年。现在的重复发生次数为。插入主定理(使用),我们得到了熟悉的解决方案:运行时间仅为。
资料来源:Dasgupta,Papadimitriou,Vazirani的算法。麦格劳-希尔。2006年。
问题
问题是要在给定的数组中找到一组给定的键。
给定:两个正整数and ,一个从to到整数的排序数组 和一个整数列表。
返回值:对于每个,输出索引st或“ -1”(如果没有这样的索引)。
Sample Dataset
5 6 10 20 30 40 50 40 10 35 15 40 20
Sample Output
4 1 -1 -1 4 2