-
Notifications
You must be signed in to change notification settings - Fork 0
/
Binary-search.py
123 lines (88 loc) · 2.9 KB
/
Binary-search.py
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
'''
Iteration Method
binarySearch(arr, x, low, high)
repeat till low = high
mid = (low + high)/2
if (x == arr[mid])
return mid
else if (x > arr[mid]) // x is on the right side
low = mid + 1
else // x is on the left side
high = mid - 1
2. Recursive Method (The recursive method follows the divide and conquers approach)
binarySearch(arr, x, low, high)
if low > high
return False
else
mid = (low + high) / 2
if x == arr[mid]
return mid
else if x > arr[mid] // x is on the right side
return binarySearch(arr, x, mid + 1, high)
else // x is on the right side
return binarySearch(arr, x, low,
Input:
N = 5
arr[] = {1 2 3 4 5}
K = 4
Output: 3
Explanation: 4 appears at index 3.
'''
# Python3 code to implement iterative Binary
# Search.
# # It returns location of x in given array arr
# def binarySearch(arr, l, r, x):
# while l <= r:
# mid = l + (r - l) // 2
# # Check if x is present at mid
# if arr[mid] == x:
# return mid
# # If x is greater, ignore left half
# elif arr[mid] < x:
# l = mid + 1
# # If x is smaller, ignore right half
# else:
# r = mid - 1
# # If we reach here, then the element
# # was not present
# return -1
# # Driver Code
# if __name__ == '__main__':
# arr = [2, 3, 4, 10, 40]
# x = 10
# # Function call
# result = binarySearch(arr, 0, len(arr)-1, x)
# if result != -1:
# print("Element is present at index", result)
# else:
# print("Element is not present in array")
# Python3 Program for recursive binary search.
# Returns index of x in arr if present, else -1
def binarySearch(arr, low, high, x):
# Check base case
if high >= low:
mid = low + (high - low) // 2
# If element is present at the middle itself
if arr[mid] == x:
return mid
# If element is smaller than mid, then it
# can only be present in left subarray
elif arr[mid] > x:
return binarySearch(arr, low, mid-1, x)
# Else the element can only be present
# in right subarray
else:
return binarySearch(arr, mid + 1, high, x)
# Element is not present in the array
else:
return -1
# Driver Code
if __name__ == '__main__':
arr = [2, 3, 4, 10, 40]
x = 10
# Function call
result = binarySearch(arr, 0, len(arr)-1, x)
if result != -1:
print("Element is present at index", result)
else:
print("Element is not present in array")