# Selection Sort
import random
import math
c = 0 # Counter for Runtime Complexity
a = [] # List of elements
n = 0 # No. of elements
def getdata_random(): # Random Input
for i in range(n):
a.append(random.randint(1,n))
def getdata_sorted(): # Sorted Input
for i in range(n):
a.append(i+1)
def getdata_reverse(): # Reverse Sorted Input
for i in range(n):
a.append(n-i)
def showdata(): # Display all elements
for i in range(n):
print(a[i],"\t",end="")
def find_max_pos(last): # Return position of max element
global c
max_val=a[0]
max_pos=0
for i in range(1,last+1):
c=c+1
if a[i]>max_val:
max_val=a[i]
max_pos=i
return(max_pos)
def selection_sort(): # Selection Sort Block
global c
for i in range(n-1,0,-1):
c=c+1
max_pos = find_max_pos(i)
temp=a[i]
a[i] = a[max_pos]
a[max_pos] = temp
# __________________________ Main Block Starts __________________________
print("\t\t\t____Selection sort____")
n = int(input("\nEnter number of elements: "))
print("\n1.Best Case\t2.Average Case\t3.Worst Case")
ch = int(input("\tEnter your choice: "))
if ch == 1: # Best Case
getdata_sorted()
print("\nBefore sorting: ")
showdata()
selection_sort()
print("\nAfter sorting: ")
showdata()
print("Theoretical Complexity: ", n)
elif ch == 2: # Average Case
getdata_random()
print("\nBefore sorting: ")
showdata()
selection_sort()
print("\nAfter sorting: ")
showdata()
print("Theoretical complexity: ",(n*n))
elif ch == 3: # Worst Case
getdata_reverse()
print("\nBefore sorting: ")
showdata()
selection_sort()
print("\nAfter sorting: ")
showdata()
print("Theoretical complexity: ", (n*n))
else:
print("\nInvalid Choice!")
print("Runtime Complexity: ", c)
No comments:
Post a Comment