I was asked to write an 'in place' Quicksort version. Created two internal functions - a recursive one and an 'in place sorting' one that chooses random pivot (Question required so), sorts the list in place and returns the pivot's index after sorting.
import random
def quicksort(lst):
def innerfunc(lst, start=0, end=(len(lst) - 1)):
temporal_pivot = subfunc(lst, start, end)
if (end - start > 1):
if (temporal_pivot == start or temporal_pivot == start + 1):
innerfunc(lst, temporal_pivot + 1, end)
elif (temporal_pivot == end or temporal_pivot == end - 1):
innerfunc(lst, 0 , temporal_pivot - 1)
else:
innerfunc(lst, 0 , temporal_pivot - 1), innerfunc(lst, temporal_pivot + 1, end)
def subfunc(l, start, end):
i_random = random.randint(start, end) # chooses random index!
l[i_random], l[start] = l[start], l[i_random]
i_pivot = start
pivot = l[start]
i = end
while i > i_pivot:
if l[i] <= pivot:
l.insert(i_pivot, l[i])
i_pivot += 1
l.pop(i + 1)
else:
i = i - 1
return i_pivot
return innerfunc(lst)
The problem is running time -
Lists that contain 100 elements or more are sorted very slowly.
Do you have an Idea how to improve "subfunc" algorithm and my Quicksort performance?
Thank you!
Oren