Linear Search -
def linear_search(list, value):
for i in range(len(list)):
if list[i] == value:
return i
return -1
list = [1, 2, 3, 4, 5]
index = linear_search(list, 123)
if index == -1:
print("not found")
else:
print("value found at - ", index+1)
Bubble Sort -
def bubble_sort(list):
for i in range(len(list) - 1):
for j in range(len(list) - i - 1):
if list[j] > list[j + 1]:
list[j], list[j + 1] = list[j + 1], list[j]
return list
list1 = [19, 13, 6, 2, 18, 8]
bubble_sort(list1)
print(list1)
Binary Search -
def binary_search(list, value):
low = 0
high = len(list) - 1
while low <= high:
mid = (low + high) // 2
if list[mid] == value:
return mid
elif list[mid] < value:
low = mid + 1
else:
high = mid - 1
return -1
list1 = [2, 6, 8, 13, 18, 19]
z = binary_search(list1, 6)
if z == -1:
print("not tjere")
else:
print("tjere", z+1)