-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexponential_search.py
More file actions
51 lines (31 loc) · 1003 Bytes
/
exponential_search.py
File metadata and controls
51 lines (31 loc) · 1003 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
48
49
50
51
"""
This program finds an element in a sorted array
"""
def binary_search(arr, low, high, element):
if high >= low:
mid = int((low + high) / 2)
if arr[mid] == element:
return mid
if arr[mid] > element:
return binary_search(arr, low, mid - 1, element)
return binary_search(arr, mid + 1, high, element)
return False
def exponential_search(arr, length, element):
if arr[0] == element:
return 0
i = 1
while i < length and arr[i] < element:
i *= 2
return binary_search(arr, i / 2, min(i, length), element)
array = []
elements = int(input('Enter the number of elements in the array: '))
for i in range(elements):
array.append(int(input("Enter array element: ")))
array.sort()
x = int(input('Enter element to search: '))
result = exponential_search(array, elements, x)
if result:
print('The element is present at index: ', result)
else:
print('The element is not present.')
input()