Insertion Sort
Insertion Sort
def inssort(arr):
n=len(arr)
for i in range(1,n):
ele=arr[i]
j=i-1
while ele<arr[j] and j>=0:
arr[j+1]=arr[j]
j=j-1
arr[j+1]=ele
return arr
l=[4,1,7,2,3,8,9,6]
print(inssort(l))
Selection Sort
def selsort(arr):
n=len(arr)
for i in range(0,n-1):
sm=arr[i]
pos=i
for j in range(i+1,n):
if arr[j]<sm:
sm=arr[j]
pos=j
arr[i],arr[pos]=arr[pos],arr[i]
return arr
l=[9,3,1,6,2,4,8,7]
print(selsort(l))
Bubble Sort
def bubsort(arr):
n=len(arr)
for i in range(0,n):
for j in range(0,n-i-1):
if arr[j+1]<arr[j]:
arr[j+1],arr[j]=arr[j],arr[j+1]
return arr
l=[9,3,1,6,2,4,8,7]
print(bubsort(l))
def linearSearch(array, n, x):
for i in range(0, n):
if (array[i] == x):
return i
return -1
def binarySearch(array, x, low, high):
# Repeat until the pointers low and high meet each other
while low <= high:
mid = low + (high - low)//2
if array[mid] == x:
return mid
elif array[mid] < x:
low = mid + 1
else:
high = mid - 1
return -1