RosettaCodeData/Task/Binary-search/Brat/binary-search.brat

32 lines
600 B
Text
Raw Permalink Normal View History

2013-04-10 16:19:29 -07:00
binary_search = { search_array, value, low, high |
2013-06-05 21:47:54 +00:00
true? high < low
{ null }
{
mid = ((low + high) / 2).to_i
true? search_array[mid] > value
{ binary_search search_array, value, low, mid - 1 }
{ true? search_array[mid] < value
{ binary_search search_array, value, mid + 1, high }
{ mid }
}
}
2013-04-10 16:19:29 -07:00
}
#Populate array
2013-06-05 21:47:54 +00:00
numbers = 1000.of { random 1000 }
2013-04-10 16:19:29 -07:00
#Sort the array
numbers.sort!
#Find a number
x = random 1000
p "Looking for #{x}"
2013-06-05 21:47:54 +00:00
index = binary_search numbers, x, 0, numbers.length - 1
2013-04-10 16:19:29 -07:00
null? index
{ p "Not found" }
{ p "Found at index: #{index}" }