vendredi 8 mai 2015

puts "nil" if it is not in range

def binary_search(num, test_array)
  counter = 0
  low = 0
  high = test_array.length

  while (low <= high) do
    i = ((low + high) / 2).floor;
    if num == test_array[i]
      return i
      break
    elsif num < test_array[i]
      high = i
    elsif num > test_array[i]
      low = i
    end
    counter += 1
  end
end

test_array = [13, 19, 24, 29, 32, 37, 43]
# binary_search(35, test array)?
# binary_search(11, test array)?

in this code, how can I make sure it will return "nil" if it is binary_search(35), or binary_search(11)?

Aucun commentaire:

Enregistrer un commentaire