Apply quickselect to find the median of the list of numbers

Apply quickselect to find the median of the list of numbers 9, 12, 5, 17, 30, 8.

Solution

def quick_select(numbers, k):
if len(numbers) != 0:
pivot = numbers[(len(numbers)) // 2]
small = []
for i in numbers:
if i < pivot:
small.append(i)
large = []
for i in numbers:
if i > pivot:
large.append(i)
count = len(numbers) - len(small) - len(large)
m = len(small)
if k >= m and k < m + count:
return pivot
print(pivot)
elif m > k:
return quick_select(small, k)
else:
return quick_select(large, k-m-count)

numbers = [9, 12, 5, 17, 30, 8]
k = len(numbers) // 2

print(quick_select(numbers, k))

\"\"\"

sample output:

12

\"\"\"

Apply quickselect to find the median of the list of numbers 9, 12, 5, 17, 30, 8.Solutiondef quick_select(numbers, k): if len(numbers) != 0: pivot = numbers[(len

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site