0
votes

From my understanding in quicksort is that you pick the right most element as the pivot initially and move elements greater than the pivot to the right of the pivot and elements less than the pivot to the left of the pivot. Once the pivot is moved to right spot lets say in the middle, the array is split in half where you recursively sort the two array halves starting in the beginning and ending before the pivot and starting after the pivot to the end of the array using the same steps as previously stated. I keep getting a type error "TypeError: can only assign an iterable" when assigning the following two lines of code to sort the two array halves.

Problematic code

array[:pivot] = quicksort(array[:pivot])
array[pivot+1:] = quicksort(array[pivot+1:])

Full Code

def quicksort(array):
    
    if len(array) >1 :
        
        low = 0;
        pivot = len(array) -1;
    
        while low < pivot:
            if array[low] > array[pivot]:
        
                tempPivot = array[pivot]
                tempLow = array[low]
                tempPivotPrev = array[pivot-1]
                
                array[pivot] = tempLow
                array[pivot-1] = tempPivot
                array[low] = tempPivotPrev
                
                
                pivot=-1
            else:
                low=+1
                
            array[:pivot] = quicksort(array[:pivot])
            array[pivot+1:] = quicksort(array[pivot+1:])

    
        return array

test = [21, 4, 1, 3, 9, 20, 25, 6, 21, 14]
print quicksort(test)
1
In the last iteration quicksort returns None - and the assignment becomes array[:1] = None - that is causing the error. Print array right before those recursions. - wwii
What is your base case? - wwii
Put some print statements in - your code it doesn't look like what you described in words. - something like print(f'low:{low} pivot:{pivot} {array}') as the first while loop statement, maybe a couple more.. Here is a visual example, it might make it easier to implement - youtube.com/watch?v=ywWBy6J5gz8 - wwii

1 Answers

0
votes

Turns out my comparison logic to compare the pivot and elements was incorrect and I should be recursively sorting the two halves after the while loop.

def quicksort(array):

    
    if len(array) >1:
        
        pivot = len(array) - 1
        low = 0

        while low < pivot:
            if array[low]>array[pivot]:
                tempPivot = array[pivot]
                tempLow = array[low]
                array[low] = array[pivot-1]
                array[pivot] = tempLow
                array[pivot-1] = tempPivot
                pivot -= 1
            else:
                low += 1
       
        array[:pivot] = quicksort(array[:pivot])
        array[pivot+1:] = quicksort(array[pivot+1:])
        
    return array
        
            
        

test = [21, 4, 1, 3, 9, 20, 25, 6, 21, 14]
print quicksort(test)