I initially used only one random rod given
pivots = random.randrange(l,r)
Here l and r will be integers that define my range
I wanted to improve runtime by significantly increasing the likelihood that my rod would become a good rod by choosing the median of three random turns. Below is the code I used, and this caused my startup time to increase by 20% -30%.
rr = random.randrange
pivots = [ rr(l,r) for i in range(3) ]
pivots.sort()
How to implement the above to be much faster?
Edit: all code added below
import random
def quicksort(array, l=0, r=-1):
if r == -1:
r = len(array)
if r-l <= 1:
return
rr = random.randrange
pivots = [ rr(l,r) for i in range(3) ]
pivots.sort()
i = l+1
array[l], array[pivots[1]] = array[pivots[1]], array[l]
for j in range(l+1,r):
if array[j] < array[l]:
array[i], array[j] = array[j], array[i]
i = i+1
array[l], array[i-1] = array[i-1], array[l]
quicksort(array, l, i-1)
quicksort(array, i, r)
return array
Edit 2: This is a fixed code. Error in the algorithm for selecting 3 control points
import random
def quicksort(array, l=0, r=-1):
if r == -1:
r = len(array)
if r-l <= 1:
return
mid = int((l+r)*0.5)
pivot = 0
if array[l] > array[mid]:
if array[r-1]> array[l]:
pivot = l
elif array[mid] > array[r-1]:
pivot = mid
else:
if array[r-1] > array[mid]:
pivot = mid
else:
pivot = r-1
i = l+1
array[l], array[pivot] = array[pivot], array[l]
for j in range(l+1,r):
if array[j] < array[l]:
array[i], array[j] = array[j], array[i]
i = i+1
array[l], array[i-1] = array[i-1], array[l]
quicksort(array, l, i-1)
quicksort(array, i, r)
return array