linear search
def linearsearch(arr, x):
for i in range(len(arr)):
if arr[i] == x:
return i
return -1
arr = ['t','u','t','o','r','i','a','l']
x = 'a'
print("element found at index "+str(linearsearch(arr,x)))
binary search
def binarySearch(array, x, low, high):
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
array = [3, 4, 5, 6, 7, 8, 9]
x = 4
result = binarySearch(array, x, 0, len(array)-1)
if result != -1:
print("Element is present at index " + str(result))
else:
print("Not found")
selection sort
def selectionSort( itemsList ):
n = len( itemsList )
for i in range( n - 1 ):
minValueIndex = i
for j in range( i + 1, n ):
if itemsList[j] < itemsList[minValueIndex] :
minValueIndex = j
if minValueIndex != i :
temp = itemsList[i]
itemsList[i] = itemsList[minValueIndex]
itemsList[minValueIndex] = temp
return itemsList
el = [21,6,9,33,3]
print(selectionSort(el))
bubble sort
def bubbleSort( theSeq ):
n = len( theSeq )
for i in range( n - 1 ) :
flag = 0
for j in range(n - 1) :
if theSeq[j] > theSeq[j + 1] :
tmp = theSeq[j]
theSeq[j] = theSeq[j + 1]
theSeq[j + 1] = tmp
flag = 1
if flag == 0:
break
return theSeq
el = [21,6,9,33,3]
result = bubbleSort(el)
print (result)
insertion sort
def insertionSort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i-1
while j >=0 and key < arr[j] :
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
arr = ['h','e','l','l','o']
insertionSort(arr)
print ("The sorted array is:")
for i in range(len(arr)):
print (arr[i])
fibonacci algorithm
def Fibonacci(n):
if n<= 0:
print("Incorrect input")
elif n == 1:
return 0
elif n == 2:
return 1
else:
return Fibonacci(n-1)+Fibonacci(n-2)
print(Fibonacci(10))