Skip to content

Instantly share code, notes, and snippets.

@Lupeipei
Created October 3, 2017 13:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Lupeipei/0afd68952413b38d4cb0ce927f9f9d66 to your computer and use it in GitHub Desktop.
Save Lupeipei/0afd68952413b38d4cb0ce927f9f9d66 to your computer and use it in GitHub Desktop.
binary_search method
require 'benchmark'
def binary_search(arr, element)
b = arr.sort
if b.include?(element)
return b.bsearch_index {|x| x >= element}
end
end
arr1 = Array.new(10){rand(100)}
arr2 = Array.new(10000){rand(100000)}
arr3 = Array.new(1000000){rand(10000000)}
Benchmark.bm do |x|
x.report("arr1") {binary_search(arr1,371)}
x.report("arr2") {binary_search(arr2,371)}
x.report("arr3") {binary_search(arr3,371)}
end
arr = [0, 5, 13, 13, 30, 42, 52, 70, 85, 96, 103, 111, 116, 127, 130, 143, 150, 150, 161, 175, 207, 210, 218, 246, 257, 257, 263, 280, 304, 310, 326, 327, 332, 346, 360, 371, 374, 378, 406, 407, 407, 408, 428, 431, 437, 442, 445, 479, 489, 491, 505, 517, 520, 536, 548, 598, 602, 605, 618, 642, 649, 654, 659, 662, 677, 678, 682, 689, 695, 696, 697, 701, 711, 717, 727, 737, 745, 749, 754, 757, 770, 786, 802, 805, 814, 832, 840, 850, 853, 854, 888, 894, 904, 913, 913, 945, 962, 964, 972, 998]
puts binary_search(arr, 371)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment