Jump to content

Featured Replies

I'm newbie to algorithms and also was working upon developing a Quick Sort algorithm with such a duplex partition to ensure that it works quickly even on sequences with many equal components. My approach was as follows:

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 doesn't provide properly sorted lists. after following through this article I discovered the right partition code implementation.

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

Could you please clarify why the wrong partition implementation failed? Thank you in advance.

Edited by Phi for All
commercial links removed by moderator

Please sign in to comment

You will be able to leave a comment after signing in

Sign In Now

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.