-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_search_algorithm.rb
More file actions
38 lines (34 loc) · 1018 Bytes
/
Copy pathbinary_search_algorithm.rb
File metadata and controls
38 lines (34 loc) · 1018 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#Improve Performance
#Reduce Time complexity
#Binary Search - The Elements are sorted order
#This is faster than binary search. Because, This is checking mid of the element
#Apllicable for single array
def sorted_binary_search(arr, key)
least = 0
high = arr.length - 1
while(least <= high)
mid = least + ((high-least)/2)
puts "arr: #{arr[mid]} mid: #{mid} least: #{least} high: #{high}"
if arr[mid] == key
return mid
elsif arr[mid] < key
least = mid + 1
else
high = mid - 1
end
end
return "The value is not there"
end
Note: Do Benchmarking for this
EXAMPLE: sorted_binary_search((333..555).to_a, 445)
OUTPUT:
arr: 666 mid: 333 least: 0 high: 666
arr: 833 mid: 500 least: 334 high: 666
arr: 916 mid: 583 least: 501 high: 666
arr: 958 mid: 625 least: 584 high: 666
arr: 979 mid: 646 least: 626 high: 666
arr: 989 mid: 656 least: 647 high: 666
arr: 994 mid: 661 least: 657 high: 666
arr: 997 mid: 664 least: 662 high: 666
arr: 998 mid: 665 least: 665 high: 666
=> 665