0

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

4
  • There's not a lot of point in doing i-=1 inside that for loop since i will get reset on the next loop iteration. BTW, you should fix your indentation. Commented May 5, 2018 at 14:29
  • So , in a for loop, i-=1 will not hold the counter i in place? Commented May 5, 2018 at 14:30
  • No, it won't. See here for a demo I posted a little while ago. Commented May 5, 2018 at 14:32
  • 1
    j looks like it is incremented in the wrong place. Also, if this is a 3 part quicksort, shouldn't the recursive main part of the function call itself 3 times? Your missing randomized_quick_sort(a, m1 + 1, m2 - 1); Commented May 5, 2018 at 14:35

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.