Advertisement
Guest User

Untitled

a guest
Jul 25th, 2017
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.08 KB | None | 0 0
  1. require 'benchmark'
  2.  
  3. def get_limits(a)
  4. [0, a.length - 1]
  5. end
  6.  
  7. def binary_search(a, value)
  8. first, last = get_limits(a)
  9. while first < last
  10. mid = (first + last) / 2
  11. if a[mid] == value
  12. return mid
  13. break
  14. elsif a[mid] < value
  15. first = mid + 1
  16. else
  17. last = mid
  18. end
  19. end
  20. end
  21.  
  22. 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]
  23. puts binary_search(arr, 371)
  24. arr1 = Array.new(10){rand(10)}.sort
  25. arr2 = Array.new(10000){rand(10000)}.sort
  26. arr3 = Array.new(1000000){rand(1000000)}.sort
  27.  
  28.  
  29. Benchmark.bm do |x|
  30. x.report{binary_search(arr1, 4)}
  31. x.report{binary_search(arr2, 4000)}
  32. x.report{binary_search(arr3, 400000)}
  33. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement