just having fun at this point with sorting algos. this file contains all sorting algos in our syllabus (selection sort, quick sort, bubble sort) and top 5 function
This commit is contained in:
parent
af2ac9af01
commit
582e9aa59e
66
all-sorting-algorithms (selection, bubble, quick).py
Normal file
66
all-sorting-algorithms (selection, bubble, quick).py
Normal file
@ -0,0 +1,66 @@
|
||||
# ALL SORTING ALGORITHMS
|
||||
|
||||
# Selection sort
|
||||
def selectionSort(arr):
|
||||
for i in range(len(arr)):
|
||||
min = i
|
||||
for j in range(i+1, len(arr)):
|
||||
if (arr[j] < arr[min]):
|
||||
min = j
|
||||
temp = arr[i]
|
||||
arr[i] = arr[min]
|
||||
arr[min] = temp
|
||||
print(f"-----\nSorted array (using selection sort) in ascending order is:\t{arr}\n-----\n")
|
||||
|
||||
def bubbleSort(arr):
|
||||
for i in range(len(arr)):
|
||||
for j in range(0, len(arr)-i-1):
|
||||
if (arr[j] > arr[j+1]):
|
||||
temp = arr[j]
|
||||
arr[j] = arr[j+1]
|
||||
arr[j+1] = temp
|
||||
print(f"-----\nSorted array (using bubble sort) in ascending order is:\t{arr}\n-----\n")
|
||||
|
||||
def quickSort(arr):
|
||||
if len(arr) <= 0:
|
||||
return arr
|
||||
|
||||
pivot = arr[len(arr) // 2]
|
||||
|
||||
left = []
|
||||
for i in arr:
|
||||
if (i < pivot):
|
||||
left.append(i)
|
||||
middle = []
|
||||
for i in arr:
|
||||
if (i == pivot):
|
||||
middle.append(i)
|
||||
right = []
|
||||
for i in arr:
|
||||
if (i > pivot):
|
||||
right.append(i)
|
||||
return quickSort(left) + middle + quickSort(right)
|
||||
|
||||
def top5(arr):
|
||||
top_scores = quickSort(arr)
|
||||
print(f"-----\nTop five scores (sorted using quick sort) are:\t{top_scores[-1:-6:-1]}\n-----\n")
|
||||
|
||||
def main():
|
||||
marks = []
|
||||
|
||||
total = int(input("Total number of students are:\t"))
|
||||
for i in range(total):
|
||||
percen = float(input(f"Enter percentage for student {i+1}:\t"))
|
||||
marks.append(percen)
|
||||
|
||||
print(f"\n-----\nPercentages of {total} students are:\t{marks}\n-----")
|
||||
selectionSort(marks)
|
||||
bubbleSort(marks)
|
||||
print(f"\n-----\nSorted array (using quick sort) in ascending order is:\t{quickSort(marks)}\n-----\n")
|
||||
top5(marks)
|
||||
print(marks)
|
||||
|
||||
|
||||
# Calling main function
|
||||
main()
|
||||
|
Loading…
Reference in New Issue
Block a user