RosettaCodeData/Task/Binary-search/Phix/binary-search-1.phix

21 lines
493 B
Text
Raw Permalink Normal View History

2017-09-23 10:01:46 +02:00
global function binary_search(object needle, sequence haystack)
integer lo = 1,
hi = length(haystack),
mid = lo,
c = 0
while lo<=hi do
mid = floor((lo+hi)/2)
c = compare(needle, haystack[mid])
if c<0 then
hi = mid-1
elsif c>0 then
lo = mid+1
2016-12-05 23:44:36 +01:00
else
2017-09-23 10:01:46 +02:00
return mid -- found!
2016-12-05 23:44:36 +01:00
end if
2017-09-23 10:01:46 +02:00
end while
mid += c>0
return -mid -- where it would go, if inserted now
2016-12-05 23:44:36 +01:00
end function