Search code examples
pythonquicksort

I am trying to implement quicksort in Python but the output list is either skipping elements or repeating them


I am very new to programming and wanted to implement quicksort after going through diagrams given in my book. However, I am not getting the desired sorted list as some elements are either not added or are repeated. I suspect that the problem is with how I am using recursion to sort the list.

array = [52, 5, 45, 2, 78, 1, 9, 57, 3]
global less_pivot_list
global greater_pivot_list

def quicksort(array):
    global less_pivot_list
    global greater_pivot_list

    if len(array) < 2:
        return array
    elif len(array) == 2:
        if array[0] > array[1]:
            temp = array[0]
            array[0] = array[1]
            array[1] = temp
        return array 
    else:
        pivot_index = 0
        pivot = array[pivot_index]
        list_pivot = [pivot]
        less_pivot_list = [item for item in array if pivot > item]
        greater_pivot_list = [item for item in array if pivot < item]   
        return quicksort(less_pivot_list) + list_pivot + quicksort(greater_pivot_list)

output = quicksort(array)
print(output)

Here is the output: [1, 2, 3, 5, 3, 52, 3]


Solution

  • Remove the global declaration within the function

    array= [52,5,45,2,78,1,9,57,3]
    less_pivot_list = []
    greater_pivot_list = []
    
    def quicksort(array):
    
       if len(array)<2:
           return array
       elif len(array)==2:
           if array[0] > array[1]:
               temp = array[0]
               array[0] = array[1]
               array[1]= temp
           return array 
       else:
        pivot_index=0
        pivot=array[pivot_index]
        list_pivot=[pivot]
        less_pivot_list = [item for item in array if pivot > item]
        greater_pivot_list = [item for item in array if pivot < item]   
        return quicksort(less_pivot_list) +list_pivot+ quicksort(greater_pivot_list)
    
    output=quicksort(array)
    print(output)
    

    this produces the output correctly sorted.