1

I was trying to implement the in place partition subroutine of quicksort.It works with array of unique elements,but fails when the array contains duplicate elements

The code goes like this

def inplace_partitioning(input,l,r):
    len_a=len(input)
    pivot=input[l]
    i=l+1
    for j in range(l+1,r+1,1):
        if input[j]<pivot:#do nothing if new elem >pivot
            #swap new elem with leftmost elem greater than pivot
            temp=input[j]
            input[j]=input[i]
            input[i]=temp
            i+=1
    #swap pivot with rightmost elem lessthan pivot
    temp=input[l]
    input[l]=input[i-1]
    input[i-1]=temp

When the input is of unique elements,the code gives correct results

input=[5,6,3,1,8,4]
inplace_partitioning(input,0,len(input)-1)
print input

>>[4, 3, 1, 5, 8, 6]

when I tried the array below,i got wrong results

input=[5,6,3,1,8,5]
>>>[1, 3, 5, 6, 8, 5]

Is this because my implementation faulty?can someone help out a bit?

Chris Gerken
  • 16,221
  • 6
  • 44
  • 59
damon
  • 8,127
  • 17
  • 69
  • 114

3 Answers3

0

This should do it

def partitionv(arr, l, r):

    p = r
    idx = l
    for i in range(l, r-1, 1):
        if arr[i] < arr[p]:
            arr[i], arr[idx] = arr[idx], arr[i]
            idx += 1
    arr[p], arr[idx] = arr[idx], arr[p]

    return arr

this is a partition of the element on the right.

jassinm
  • 7,323
  • 3
  • 33
  • 42
0
if input[j]<pivot:

This means it will only move numbers left of the pivot if they are smaller. However you want numbers equal to the size of the pivot to be moved, otherwise numbers of equal size to the pivot will be spread throughout the right of the pivot.

change it to:

if input[j]<=pivot:
Rusty Rob
  • 16,489
  • 8
  • 100
  • 116
0

I don't quite get your algorithm, and it doesn't look like quicksort partitioning. Normally, you run i and j in different directions, one starting at the top of the interval and one at the bottom, but if I understand correctly, yours run in the same direction. In the first iteration, i and j have the same value, and if it is smaller than the pivot, it is exchanged for itself (i.e. the same effect as if it is NOT smaller than the pivot)?

njlarsson
  • 2,128
  • 1
  • 18
  • 27