In this problem, you will implement the binary search algorithm that allows searching very efficiently (even huge) lists, provided that the list is sorted.
The goal in this code problem is to implement the binary search algorithm.
The first line of the input contains an integer π and a sequence π0 < π1 < . . . < ππβ1 of π pairwise distinct positive integers in increasing order. The next line contains an integer π and π positive integers π0, π1, . . . , ππβ1.
1 β€ π β€ 105; 1 β€ π β€ 3 Β· 104; 1 β€ ππ β€ 109 for all 0 β€ π < π; 1 β€ ππ β€ 109 for all 0 β€ π < π;
For all π from 0 to π β 1, output an index 0 β€ π β€ π β 1 such that ππ = ππ or β1 if there is no such index.
- Input:
5 1 5 8 12 13
5 8 1 23 1 11
- Output:
2 0 -1 0 -1
In this sample, we are given an increasing sequence π0 = 1, π1 = 5, π2 = 8, π3 = 12, π4 = 13 of length five and five keys to search: 8, 1, 23, 1, 11. We see that π2 = 8 and π0 = 1, but the keys 23 and 11 do not appear in the sequence π. For this reason, we output a sequence 2, 0,β1, 0,β1.
def find_index(array, number)
first_index = 0
last_index = array.length - 1
while first_index <= last_index
mid_index = (first_index + last_index) / 2
array_el = array[mid_index].to_i
if array_el == number
return mid_index
elsif array_el > number
last_index = mid_index - 1
return -1 if first_index > last_index
elsif array_el < number
first_index = mid_index + 1
return -1 if first_index > last_index
end
end
end
sorted_array = gets.chomp.split
sorted_array.shift
numbers = gets.chomp.split
numbers.shift
indexes = numbers.map do |number|
find_index(sorted_array, number.to_i)
end
indexes.each do |el|
print el.to_s + " "
end