Quick Sort With Pivot At Random Element
# Q.14 Write A Python Program To Store First Year Percentage Of Students In Array.
# Write Function For Sorting Array Of Floating Point Numbers In Ascending Order Using Quick
# Sort And Display Top Five Scores
# Quick Sort
import random
def partition(arr, left, right):
randint = random.randint(left, right)
arr[randint], arr[right] = arr[right], arr[randint]
pivot = arr[right]
first = left
last = right - 1
while True:
while first <= last and arr[first] <= pivot:
first = first + 1
while first <= last and arr[last] >= pivot:
last = last - 1
if first < last:
arr[first], arr[last] = arr[last], arr[first]
else:
break
arr[right], arr[first] = arr[first], arr[right]
return first
def quickSort(arr, left, right):
if left < right:
pivotindex = partition(arr, left, right)
quickSort(arr, left, pivotindex - 1)
quickSort(arr, pivotindex + 1, right)
return arr
if __name__ == '__main__':
try:
num = int(input("Enter The Number Of Students\n"))
arr = []
for i in range(num):
userinput = int(
input(f"Enter The Percentage Of Student {i + 1}\n"))
arr.append(userinput)
print("\nUnsorted Array =", arr)
low = 0
high = num - 1
print("Sorted Array =", quickSort(arr, low, high))
print("\nTop Five Scores Are : ")
maxarr = []
i = 0
while i < num:
i = i + 1
if arr[-i] == arr[-i + 1]:
continue
maxarr.append(arr[-i])
if len(maxarr) == 5:
break
for i in range(len(maxarr)):
print(maxarr[i], "%")
except Exception as e:
print("Wrong Input, Please Enter Integers Only!!")
# Output
# Enter The Number Of Students
# 10
# Enter The Percentage Of Student 1
# 84
# Enter The Percentage Of Student 2
# 84
# Enter The Percentage Of Student 3
# 85
# Enter The Percentage Of Student 4
# 78
# Enter The Percentage Of Student 5
# 75
# Enter The Percentage Of Student 6
# 68
# Enter The Percentage Of Student 7
# 65
# Enter The Percentage Of Student 8
# 88
# Enter The Percentage Of Student 9
# 89
# Enter The Percentage Of Student 10
# 92
# Unsorted Array = [84, 84, 85, 78, 75, 68, 65, 88, 89, 92]
# Sorted Array = [65, 68, 75, 78, 84, 84, 85, 88, 89, 92]
# Top Five Scores Are :
# 92 %
# 89 %
# 88 %
# 85 %
# 84 %
Comments
Post a Comment