你的任務是實作二分搜尋演算法。
二分搜尋演算法會反覆把陣列切成兩半,只留下包含我們要找的項目的那一半,藉此在陣列中找到項目。 它可以讓我們快速縮小項目可能出現的位置,直到找到它,或是排除所有可能的位置。
二分搜尋只有在陣列已經排序過時才能運作。
這個演算法的流程如下:
來看一個例子:
假設我們要在下面這個已排序的陣列中尋找數字 23:[4, 8, 12, 16, 23, 28, 32]。
[23, 28, 32]。[23]。在測試案例中,你的解法行為應該與 Julia 內建的searchsorted函式一致。
這代表你要回傳的並不是你在陣列中找到的第一個相符元素的索引,而是一個範圍;這個範圍的下界是陣列中第一個相符元素的索引,上界則是最後一個相符元素的索引。
不過,為了簡化你的解法,你可以假設目標元素不會重複,只有多重相符的加分任務測試集例外。
如果要搜尋的項目不在陣列中,你必須回傳一個空範圍,其下界是該項目可以插入已排序陣列中的索引位置。空範圍是指上界小於下界的任何範圍。
更多細節請參閱searchsorted函式的說明文件與範例:
searchsorted(a, x; by=<transform>, lt=<comparison>, rev=false)
Return the range of indices of a which compare as equal to x (using binary
search) according to the order specified by the by, lt and rev keywords,
assuming that a is already sorted in that order.
Return an empty range located at the insertion point if a does not contain
values equal to x.
See also: insorted, searchsortedfirst, sort, findall.
Examples
julia> searchsorted([1, 2, 4, 5, 5, 7], 4) # single match
3:3
julia> searchsorted([1, 2, 4, 5, 5, 7], 5) # multiple matches
4:5
julia> searchsorted([1, 2, 4, 5, 5, 7], 3) # no match, insert in the middle
3:2
julia> searchsorted([1, 2, 4, 5, 5, 7], 9) # no match, insert at end
7:6
julia> searchsorted([1, 2, 4, 5, 5, 7], 0) # no match, insert at start
1:0
by、lt和rev,讓by指定套用到陣列中所有元素的轉換,lt指定比較方式,而rev指定陣列是否以反向排序。使用這些參數時,你必須假設陣列已經依照這些參數排序過。更多細節請參閱sort的說明文件。