Last active
October 3, 2017 10:29
-
-
Save michaelmakun/5a3ac6c03fd386e0629d5f1ed8a10ed1 to your computer and use it in GitHub Desktop.
binary_search and find_index
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'benchmark' | |
def binary_search(arr,element) | |
l = 0 | |
r = arr.length - 1 | |
while l <= r | |
mid = l + ((r-l)/2) | |
if arr[mid] == element | |
return mid | |
elsif arr[mid] > element | |
r = mid - 1 | |
else | |
l = mid + 1 | |
end | |
end | |
return "找不到对应的元素" | |
end | |
def sorted_array(length) | |
arr = Array.new(length) { rand(10000) } | |
arr.sort | |
end | |
a1 = sorted_array 10 | |
a2 = sorted_array 10_000 | |
a3 = sorted_array 1_000_000 | |
Benchmark.bm do |x| | |
x.report("10个元素的运行效果"){binary_search(a1,351)} | |
x.report("10000个元素的运行效果"){binary_search(a2,351)} | |
x.report("1000000个元素的运行效果"){binary_search(a3,351)} | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment