php - Programming In General - Binary Search Algorithms -
given array $array of n numbers , key $key, write binary search algorithm in plain english. if $array contains $key, return index of $key; otherwise, return -1.
can show me how this?
doesn't seem should give code here, maybe description can help?
sort list.
let
i = length / 2
compare term @ index
i
key.a. if equal, return index.
b. if key greater term, repeat 3 (recurse) on upper half of list
i = (i + length) / 2
(or(i + top) / 2
depending how implement)c. if key less term, repeat 3 on lower half
i = i/2
or(i + bottom)/2
stop recursion if/when new i
same old i
. means you've exhausted search. return -1
be careful off-by-one errors, can make exclude terms mistake, or cause infinite recursion, general idea. pretty straightforward.
think of playing 'guess number' numbers 1 through 100. take guess, tell higher or lower. 50, lower. 25, higher. 37...
Comments
Post a Comment