Quicksort In-Place

  • + 0 comments

    def partition(arr, first, last):

    i = (first - 1)         # last_index of smaller elements
    pivot = arr[last]     
    
    for j in range(first, last):
    
        # If current element is smaller than or equal to pivot
        if arr[j] <= pivot:
    
            # increment last_index of smaller elements
            i = i + 1
            # move the element to the last_index of smaller elements
            arr[i], arr[j] = arr[j], arr[i]
    
    arr[i + 1], arr[last] = arr[last], arr[i+1]
    print (' '.join(str(x) for x in arr))
    
    return (i + 1)
    

    def quickSort(arr, first, end):

    if len(arr) == 1:
        return arr
    if first < end:        
        pivot_index = partition(arr, first, end)        
        quickSort(arr, first, pivot_index-1)
        quickSort(arr, pivot_index+1, end)
    

    n = int(input().rstrip())

    arr = list(map(int,input().rstrip().split()))

    quickSort(arr, 0, n-1)