The searching algorithm that I created is dependent upon the sorting algorithm (which many of you have seen in my previous question). I believe that the sorting algorithm can't be better (for beginner-level programmers like me) but I would like to know what you think about my descriptions for the searching algorithm.
I would appreciate your insight on the commented sections of my code (again, for the searching algorithm). And if there are any other changes I can make, please don't hesitate to let me know.
def sorting_algorithm(list):
for index in range(1, len(list)):
current = list[index]
while index > 0 and list[index - 1] > current:
list[index] = list[index - 1]
index = index - 1
list[index] = current
return list
print("the sorted list is", (sorting_algorithm([45, 14, 1, 7, 98, 23, 102, 57])))
#SEARCHING ALGORITHM CODE:
def searching_algorithm(list, num):
fir = 0 #the first number of the list.
las = len(list)-1 #the last number of the list.
i = -1 #the index is at the last number of the list.
while (fir <= las) and (i == -1): #the first number is less than or equals to the last number and the
#index is at -1 (so the last number).
mid = (fir + las) // 2 #the middle number is equal to the first num divided by the last number
#but without the remainder part.
if list[mid] == num: #if the middle number of the list equals the number
i = mid #then the index is moved to the middle number of the list.
else: #if that isn't true then we move on to the following condition.
if num<list[mid]: #if the number is less than the middle number of the list
las = mid -1 #then the index moves one to the right.
else: #if that isn't true either, then move on to the following condition.
fir = mid +1 #then the program will conclude that the number is the greater than
#the middle number.
return i
print("your number is at index",searching_algorithm([1, 7, 14, 23, 45, 57, 98, 102], 23))