forked from jainaman224/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinary_Search.rb
More file actions
47 lines (32 loc) · 807 Bytes
/
Binary_Search.rb
File metadata and controls
47 lines (32 loc) · 807 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
39
40
41
42
43
44
45
46
47
# Binary Search function
def binarySearch(array, searchVariable, size)
left = 0
right = size - 1
while left <= right
middle = left + (right - left) / 2
if(array[middle] == searchVariable)
return middle
elsif(searchVariable < array[middle])
right = middle - 1;
else
left = middle + 1;
end
end
return -1
end
# Hard Coded array
array = [1, 2, 3, 4, 5]
# Searching for 1 in the array
if binarySearch(array, 1, array.length()) != -1
puts("Element found.")
else
puts("Element not found.")
end
# Gives Output Element found.
# Searching for 0 in the array
if binarySearch(array, 0, array.length()) != -1
puts("Element found.")
else
puts("Element not found.")
end
# Gives output Element not found.