I am new to algorithms and was working on implementing the Quick Sort algorithm with a 3-way partition such that it works fast even on sequences containing many equal elements. The following was my implementation:
def randomized_quick_sort(a, l, r):
if l >= r:
return
k = random.randint(l, r)
a[l], a[k] = a[k], a[l]
#use partition3
m1,m2 = partition3(a, l, r)
randomized_quick_sort(a, l, m1 - 1);
randomized_quick_sort(a, m2 + 1, r);
def partition3(a, l, r):
x, j, t = a[l], l, r
for i in range(l + 1, t+1):
if a[i] < x:
j += 1
a[i], a[j] = a[j], a[i]
elif a[i]>x:
a[i],a[t]=a[t],a[i]
i-=1
t-=1
a[l], a[j] = a[j], a[l]
return j,t
It does not generate correctly sorted lists. I found the correct implementation of the partition code here in Stack Overflow.
def partition3(a, l, r):
x, j, t = a[l], l, r
i = j
while i <= t :
if a[i] < x:
a[j], a[i] = a[i], a[j]
j += 1
elif a[i] > x:
a[t], a[i] = a[i], a[t]
t -= 1
i -= 1 # remain in the same i in this case
i += 1
return j,t
Can someone please explain to me how the incorrect partition implementation was failing? Thanks in advance
i-=1inside thatforloop sinceiwill get reset on the next loop iteration. BTW, you should fix your indentation.randomized_quick_sort(a, m1 + 1, m2 - 1);