Skip to content

Commit d894eac

Browse files
authored
Merge pull request Phantsure#5 from SucharuRai/master
Searching Rythms added (>> fibonacciSearch and interpolationSearch added)
2 parents d99e1ca + 2ef0803 commit d894eac

File tree

2 files changed

+85
-0
lines changed

2 files changed

+85
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
#List should be in Sorted ascending order
2+
3+
from bisect import bisect_left
4+
def fibonacciSearch(arr, x, n):
5+
6+
# Initialize fibonacci numbers
7+
m2 = 0 # (m-2)'th Fibonacci No.
8+
m1 = 1 # (m-1)'th Fibonacci No.
9+
m = m2 + m1 # m'th Fibonacci
10+
11+
# m is going to store the smallest
12+
# Fibonacci Number greater than or equal to n
13+
while (m < n):
14+
m2 = m1
15+
m1 = m
16+
m = m2 + m1
17+
18+
offset = -1;
19+
20+
while (m > 1):
21+
i = min(offset+m2, n-1)
22+
if (arr[i] < x):
23+
m = m1
24+
m1 = m2
25+
m2 = m - m1
26+
offset = i
27+
elif (arr[i] > x):
28+
m = m2
29+
m1 = m1 - m2
30+
m2 = m - m1
31+
else :
32+
return i
33+
34+
if(m1 and arr[offset+1] == x):
35+
return offset+1;
36+
return -1
37+
38+
print("Enter the elements of the array in a single line: ")
39+
arr = list(map(int,input().split()))
40+
num = int(input("Enter the number you want to search\n"))
41+
42+
ind = fibonacciSearch(arr, num, len(arr))
43+
if(ind>=0):
44+
print("Found at index: ",ind)
45+
else:
46+
print("Searched Element not found")
47+
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
#List should be in Sorted ascending order
2+
3+
def interpolationSearch(arr, n, x):
4+
# Settting indexes of two corners
5+
lo = 0
6+
hi = n
7+
8+
while (lo <= hi and x >= arr[lo] and x <= arr[hi]):
9+
if lo == hi:
10+
if arr[lo] == x:
11+
return lo;
12+
return -1;
13+
14+
pos = lo + int(((float(hi - lo) /
15+
( arr[hi] - arr[lo])) * ( x - arr[lo])))
16+
17+
18+
if arr[pos] == x:
19+
return pos
20+
21+
if arr[pos] < x:
22+
lo = pos + 1;
23+
24+
else:
25+
hi = pos - 1;
26+
27+
return -1
28+
29+
print("Enter the elements of the array in a single line: ")
30+
arr = list(map(int,input().split()))
31+
num = int(input("Enter the number you want to search\n"))
32+
33+
index = interpolationSearch(arr, len(arr)-1, num)
34+
35+
if (index != -1):
36+
print ("Element found at index ",index )
37+
else:
38+
print ("Element not found")

0 commit comments

Comments
 (0)