Skip to content

Commit b45e6b7

Browse files
committed
Implementation of Binary and Sequential Search is done via Python.
1 parent 4c0b466 commit b45e6b7

File tree

2 files changed

+100
-0
lines changed

2 files changed

+100
-0
lines changed

Search Technique/BinarySearch.py

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
__author__ = 'Sanjay'
2+
3+
4+
def binarySearch(alist, item):
5+
first = 0
6+
last = len(alist)-1
7+
found = False
8+
9+
while first<=last and not found:
10+
midpoint = (first + last)//2
11+
if alist[midpoint] == item:
12+
found = True
13+
else:
14+
if item < alist[midpoint]:
15+
last = midpoint-1
16+
else:
17+
first = midpoint+1
18+
19+
return found
20+
21+
22+
#2nd - Recursive binary search Method
23+
def binarySearch2(alist, item):
24+
if len(alist) == 0:
25+
return False
26+
else:
27+
midpoint = len(alist)//2
28+
if alist[midpoint]==item:
29+
return True
30+
else:
31+
if item<alist[midpoint]:
32+
return binarySearch(alist[:midpoint],item)
33+
else:
34+
return binarySearch(alist[midpoint+1:],item)
35+
36+
37+
38+
if __name__ == '__main__':
39+
testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42,]
40+
print(binarySearch(testlist, 3))
41+
print(binarySearch(testlist, 13))
42+

Search Technique/SequentialSearch.py

+58
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
__author__ = 'Sanjay'
2+
3+
4+
def seqSearch(aList, item):
5+
pos =0
6+
found = False
7+
8+
while pos<len(aList) and not found:
9+
if aList[pos] == item:
10+
found = True
11+
else:
12+
pos = pos +1
13+
return found
14+
15+
#as per book
16+
def sequentialSearch(alist, item):
17+
pos = 0
18+
found = False
19+
20+
while pos < len(alist) and not found:
21+
if alist[pos] == item:
22+
found = True
23+
else:
24+
pos = pos+1
25+
26+
return found
27+
28+
#sequential search for a ordered list.
29+
30+
def orderedSequentialSearch(alist, item):
31+
pos = 0
32+
found = False
33+
stop = False
34+
while pos < len(alist) and not found and not stop:
35+
if alist[pos] == item:
36+
found = True
37+
else:
38+
if alist[pos] > item:
39+
stop = True
40+
else:
41+
pos = pos+1
42+
43+
return found
44+
45+
testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42,]
46+
print(orderedSequentialSearch(testlist, 3))
47+
print(orderedSequentialSearch(testlist, 13))
48+
49+
50+
51+
52+
if __name__ == '__main__':
53+
s= [1,2,32,42,12,4,3,45,454]
54+
print(seqSearch(s,45))
55+
56+
testlist = [1, 2, 32, 8, 17, 19, 42, 13, 0]
57+
print(sequentialSearch(testlist, 3))
58+
print(sequentialSearch(testlist, 13))

0 commit comments

Comments
 (0)