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)?
在此代码中,我如何确保它将返回&#34; nil&#34;如果是binary_search(35)或binary_search(11)?
答案 0 :(得分:1)
正如@YuHao指出的那样,当你的元素找不到时,它是一个无限循环:low = high = 0
(在低端),这使循环无限期地运行。
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
elsif num < test_array[i]
high = i
elsif num > test_array[i]
low = i
end
counter += 1
break if counter > test_array.length / 2 # could probably be more efficient
end
nil
end
test_array = [13, 19, 24, 29, 32, 37, 43]
binary_search(11, test_array) # => nil
binary_search(35, test_array) # => nil
答案 1 :(得分:0)
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
# check for value not found
if (high - low) <= 1
return nil
end
end
end