Search code examples
pythonalgorithmsortingquicksort

quicksort in python always return a unsorted array


i defined a quicksort in python.It printed a sorted list, but the return list is unsorted. [1, 5, 7, 8] #this is result of print(array) in quicksort [7, 5, 8, 1] #this is result of testing it's so weired

def quickSort(array):
    if len(array) <= 1:
        return array

    p = 0  #pivot
    pointer = p + 1
    left = []
    pivot = []
    right = []
    pivot.append(array[p])
    
    #devide array into 3 arrays
    while pointer < len(array):
        if array[pointer] < array[p]:
            left.append(array[pointer])
        elif array[pointer] > array[p]:
            right.append(array[pointer])
        else:
            pivot.append(array[pointer])
            #pointer moves towards right
        pointer += 1
    
    print(left)
    print(pivot)
    print(right)
    array = quickSort(left) + pivot + quickSort(right)
    print(array)
    #concatenation of the 3 arrays
    return (array)
    
array = [7,5,8,1] 
quickSort(array)
print(array)

Solution

  • In the event that you pass arguments like whole numbers, strings or tuples to a function, the passing is like call-by-value because you can not change the value of the immutable objects being passed to the function.

    Example:-

    string = "Yash"
    def test(string):
        string = "Yash Mehta"
        print("Inside Function:", string)
    
    test(string)  #Yash Mehta
    print("Outside Function:", string) #Yash
    

    you can store the answer by making another variable which store list..

    def quickSort(array):
        if len(array) <= 1:
            return array
        p = 0  #pivot
        pointer = p + 1
        left = []
        pivot = []
        right = []
        pivot.append(array[p])
        
        #dvide array into 3 arrays
        while pointer < len(array):
            if array[pointer] < array[p]:
                left.append(array[pointer])
            elif array[pointer] > array[p]:
                right.append(array[pointer])
            else:
                pivot.append(array[pointer])
                #pointer moves towards right
            pointer += 1
        
        print(left)
        print(pivot)
        print(right)
        array = quickSort(left) + pivot + quickSort(right)
        print(array)
        #concatenation of the 3 arrays
        return array
        
    array = [7,5,8,1] 
    sorted_array=quickSort(array)
    print(sorted_array)
    

    Output:

    [5, 1]
    [7]
    [8]
    [1]
    [5]
    []
    [1, 5]
    [1, 5, 7, 8]
    [1, 5, 7, 8]