Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit e07fb42

Browse files
committed
searching algorithm added
1 parent 004d0f6 commit e07fb42

File tree

3 files changed

+68
-0
lines changed

3 files changed

+68
-0
lines changed

Searching/issorted.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
# determine if a list is sorted
2+
3+
4+
items1 = [6, 8, 19, 20, 23, 41, 49, 53, 56, 87]
5+
items2 = [6, 20, 8, 19, 56, 23, 87, 41, 49, 53]
6+
7+
def is_sorted(itemlist):
8+
# using the all function
9+
return all(itemlist[i] <= itemlist[i+1] for i in range(len(itemlist)-1))
10+
11+
# using the brute force method
12+
# for i in range(0, len(itemlist)-1):
13+
# if (itemlist[i] > itemlist[i+1]):
14+
# return False
15+
# return True
16+
17+
print(is_sorted(items1))
18+
print(is_sorted(items2))
19+

Searching/ordered.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# searching for an item in an ordered list
2+
# this technique uses a binary search
3+
4+
5+
items = [6, 8, 19, 20, 23, 41, 49, 53, 56, 87]
6+
7+
def binarysearch(item, itemlist):
8+
# get the list size
9+
listsize = len(itemlist) - 1
10+
# start at the two ends of the list
11+
lowerIdx = 0
12+
upperIdx = listsize
13+
14+
while lowerIdx <= upperIdx:
15+
# calculate the middle point
16+
midPt = (lowerIdx + upperIdx)// 2
17+
18+
# if item is found, return the index
19+
if itemlist[midPt] == item:
20+
return midPt
21+
# otherwise get the next midpoint
22+
if item > itemlist[midPt]:
23+
lowerIdx = midPt + 1
24+
else:
25+
upperIdx = midPt - 1
26+
27+
if lowerIdx > upperIdx:
28+
return None
29+
30+
31+
print(binarysearch(23, items))
32+
print(binarysearch(87, items))
33+
print(binarysearch(250, items))

Searching/unordered.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
# searching for an item in an unordered list
2+
# sometimes called a Linear search
3+
4+
# declare a list of values to operate on
5+
items = [6, 20, 8, 19, 56, 23, 87, 41, 49, 53]
6+
7+
def find_item(item, itemlist):
8+
for i in range(0, len(itemlist)):
9+
if item == itemlist[i]:
10+
return i
11+
12+
return None
13+
14+
15+
print(find_item(87, items))
16+
print(find_item(250, items))

0 commit comments

Comments
 (0)