Advertisement
Guest User

Untitled

a guest
Jul 26th, 2017
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.19 KB | None | 0 0
  1. require 'benchmark'
  2.  
  3. def binary_search(arr, element)
  4. index = nil
  5. first = 0
  6. last = arr.size-1
  7. while first <= last
  8. medium = (last + first)/2
  9. if arr[medium] < element
  10. first = medium + 1
  11. elsif arr[medium] > element
  12. last = medium - 1
  13. else
  14. index = medium
  15. break
  16. end
  17. end
  18.  
  19. return index
  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. p binary_search(arr, 371)
  24. a1 = Array.new(10){ rand(1000) }.sort
  25. a2 = Array.new(100){ rand(1000) }.sort
  26. a3 = Array.new(1000){ rand(1000) }.sort
  27. a4 = Array.new(1000000){ rand(1000) }.sort
  28.  
  29.  
  30. Benchmark.bm do |x|
  31. x.report {
  32. binary_search(a1, 371)
  33. }
  34. x.report {
  35. binary_search(a2, 371)
  36. }
  37. x.report {
  38. binary_search(a3, 371)
  39. }
  40. x.report {
  41. binary_search(a4, 371)
  42. }
  43. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement