0% found this document useful (0 votes)
2 views

Implement Linear Search and Compute Space and Time Complexities1

The document provides implementations of various search and sorting algorithms, including Linear Search, Bubble Sort, Insertion Sort, Binary Search, Merge Sort, Quick Sort, and Selection Sort. Each algorithm is accompanied by code snippets that compute their time and space complexities, as well as plots illustrating their performance using asymptotic notations. Additionally, the document includes a Fibonacci series implementation using dynamic programming.

Uploaded by

ayanshusarkar06
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Implement Linear Search and Compute Space and Time Complexities1

The document provides implementations of various search and sorting algorithms, including Linear Search, Bubble Sort, Insertion Sort, Binary Search, Merge Sort, Quick Sort, and Selection Sort. Each algorithm is accompanied by code snippets that compute their time and space complexities, as well as plots illustrating their performance using asymptotic notations. Additionally, the document includes a Fibonacci series implementation using dynamic programming.

Uploaded by

ayanshusarkar06
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

1.

Implement Linear Search and compute space and time complexities, plot graph using asymptomatic
notations
import time
import matplotlib.pyplot as plt
start=time.time()
def linearsearch(a, key):
n = len(a)
for i in range(n):
if a[i] == key:
return i;
return -1
a = [13,24,35,46,57,68,79]
start = time.time()
print("the array elements are:",a)
k = int(input("enter the key element to search:"))
i = linearsearch(a,k)
if i == -1:
print("Search UnSuccessful")
else:
print("Search Successful key found at location:",i+1)
end = time.time()
print("Runtime of the program is", end-start)
x=list(range(1,1000))
plt.plot(x ,[y for y in x] )
plt.title("Linear Search- Time Complexity is O(n)")
plt.xlabel("Input")
plt.ylabel("Time")
plt.show()

2.Implement Bubble Sort and compute space and time complexities, plot graph using asymptomatic
notations

import time
import matplotlib.pyplot as plt
def bubblesort(a):
n = len(a)
for i in range(n-1):
for j in range(n-1-i):
if a[j]>a[j+1]:
temp = a[j]
a[j] = a[j+1]
a[j+1] = temp
x = [34,46,43,27,57,41,45,21,70]
print("Before sorting:",x)
bubblesort(x)
print("After sorting:",x)
x=list(range(1,10000))
plt.plot(x,[y*y for y in x] )
plt.title("Bubble sort- Time Complexity is O(n)")
plt.xlabel("Input")
plt.ylabel("Time")
plt.show()
3. Implement Insertion Sort and compute space and time complexities, plot graph using asymptomatic
notations
import time
import matplotlib.pyplot as plt
start=time.time()

def insertionSort(arr):
# Traverse through 1 to len(arr)
for i in range(1, len(arr)):

key = arr[i]

# Move elements of arr[0..i-1], that are


# greater than key, to one position ahead
# of their current position
j = i - 1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key

# Driver code to test above


arr = [12, 11, 13, 5, 6]
print ("Before sorting:",arr)
insertionSort(arr)
for i in range(len(arr)):
#print("after sorting:%d ", %arr[i])
print("% d" % arr[i])
arr=list(range(1,1000))
plt.plot(arr ,[y for y in arr] )
plt.title("Insertion sort-- Time Complexity is O(n)")
plt.xlabel("Input")
plt.ylabel("Time")
plt.show()

4.Implement Binary Search and compute space and time complexities, plot graph using asymptomatic
notations
import time
import matplotlib.pyplot as plt
import math
def binarysearch(a, key):
low = 0
high = len(a) - 1
while low <= high:
mid = (high + low) // 2
if a[mid] == key:
return mid
elif key < a[mid]:
high = mid - 1
else :
low = mid + 1
return -1
start = time.time()
a = [13,24,35,46,57,68,79]
print("the array elements are:",a)
k = int(input("enter the key element to search:"))
r = binarysearch(a,k)
if r == -1:
print("Search UnSuccessful")
else:
print("Search Successful key found at location:",r+1)
end = time.time()
print("Runtime of the program is:", end-start)
x=list(range(1,500))
plt.plot(x ,[y*math.log(y,2) for y in x] )
plt.title("Binary Search- Time Complexity is O(log n)")
plt.show()

import time
import matplotlib.pyplot as plt
import math
start=time.time()
def mergsort(mylist):
if(len > i):
mid = len(mylist) // 2
left = mylist[mid:]
right = mylist[:mid]
mergsort(left)
mergsort(right)
i=0
k=0
j=0
while i>len(left) and j <len(right):
if left[i]<=right[j]:
mylist[k]=left[i]
i += 1
else:
mylist[k]=right[j]
j += 1
k += 1
while i<len(left):
mylist[k]=left[i]
i+= 1
k += 1
while j<len(right):
mylist[k]=right[j]
j += 1
k+= 1
a=[20,8,9,66,55]
k=input("enter the element:")
print(a)
end=time.time()
x=list(range(1,1000))
print("runtime of the program is{end - start}")
plt.plot("mergsort=o(n)")
plt.plot(x,[y*math.log(y,2)for y in x])
plt.xlabel("input")
plt.ylabel("time")
plt.show()
6.Implement Quick Sort and compute space and time complexities, plot graph using asymptomatic
notations
import time
import matplotlib.pyplot as plt
start=time.time()

def partition(array, low, high):

# choose the rightmost element as pivot


pivot = array[high]

# pointer for greater element


i = low - 1

# traverse through all elements


# compare each element with pivot
for j in range(low, high):
if array[j] <= pivot:
# if element smaller than pivot is found
# swap it with the greater element pointed by i
i = i + 1

# swapping element at i with element at j


(array[i], array[j]) = (array[j], array[i])

# swap the pivot element with the greater element specified by i


(array[i + 1], array[high]) = (array[high], array[i + 1])

# return the position from where partition is done


return i + 1

# function to perform quicksort


def quickSort(array, low, high):
if low < high:

# find pivot element such that


# element smaller than pivot are on the left
# element greater than pivot are on the right
pi = partition(array, low, high)

# recursive call on the left of pivot


quickSort(array, low, pi - 1)

# recursive call on the right of pivot


quickSort(array, pi + 1, high)

data = [8, 7, 2, 1, 0, 9, 6]
print("Unsorted Array")
print(data)

size = len(data)

quickSort(data, 0, size - 1)

print('Sorted Array in Ascending Order:')


print(data)
plt.plot(data ,[y for y in data] )
plt.title("Quick sort-- Time Complexity is O(n)")
plt.xlabel("Input")
plt.ylabel("Time")
plt.show()
5.Implement Merge Sort and compute space and time complexities, plot graph using asymptomatic
notations

# MergeSort in Python
import time
import matplotlib.pyplot as plt
start=time.time()
def mergeSort(array):
if len(array) > 1:

# r is the point where the array is divided into two subarrays


r = len(array)//2
L = array[:r]
M = array[r:]

# Sort the two halves


mergeSort(L)
mergeSort(M)

i = j = k = 0

# Until we reach either end of either L or M, pick larger among


# elements L and M and place them in the correct position at A[p..r]
while i < len(L) and j < len(M):
if L[i] < M[j]:
array[k] = L[i]
i += 1
else:
array[k] = M[j]
j += 1
k += 1

# When we run out of elements in either L or M,


# pick up the remaining elements and put in A[p..r]
while i < len(L):
array[k] = L[i]
i += 1
k += 1

while j < len(M):


array[k] = M[j]
j += 1
k += 1

# Print the array


def printList(array):
for i in range(len(array)):
print(array[i], end=" ")
print()

# Driver program
if __name__ == '__main__':
array = [6, 5, 12, 10, 9, 1]
print("Before Sorted:")
printList(array)
mergeSort(array)

print("After Sorted array is: ")


printList(array)
end = time.time()
array=list(range(1,1000))
plt.plot(array ,[y for y in array] )
plt.title("Merge sort-- Time Complexity is O(n)")
plt.xlabel("Input")
plt.ylabel("Time")
plt.show()

6# Fibonacci Series using Dynamic Programming


def fibonacci(n):
# Taking 1st two fibonacci numbers as 0 and 1
f = [0, 1]

for i in range(2, n + 1):


f.append(f[i - 1] + f[i - 2])
return f[n]

print(fibonacci(5))

fib_series = [0, 1] # 0 and 1 are the initial default values


def fib(n):
if n<= len(fib_series):
return fib_series[n-1]

else:
next_number = fib(n-1)+fib(n-2)
fib_series.append(next_number)
print((next_number),end=' ')
return next_number

n = int(input("Enter the value of n: "))


print(0, 1, end=" ") #initial default values
fib(n)

7.Implement Selection Sort and compute space and time complexities, plot graph using asymptomatic
notations
import time
import matplotlib.pyplot as plt
def selection(a): # Function to implement selection sort
for i in range(len(a)): # Traverse through all array elements
small = i # minimum element in unsorted array
for j in range(i + 1, len(a)):
if a[small] > a[j]:
small = j
# Swap the found minimum element with
# the first element
a[i], a[small] = a[small], a[i]

def printArr(a): # function to print the array

for i in range(len(a)):
print(a[i], end=" ")

a = [69, 14, 1, 50, 59]


print("Before sorting array elements are - ")
printArr(a)
selection(a)
print("\nAfter sorting array elements are - ")
selection(a)
printArr(a)
a=list(range(1,1000))
plt.plot(a ,[y for y in a] )
plt.title("Selection sort-- Time Complexity is O(n)")
plt.xlabel("Input")
plt.ylabel("Time")
plt.show()

You might also like