Open In App

Python Program for Iterative Quick Sort

Improve
Improve
Like Article
Like
Save
Share
Report

The code consists of two main functions: partition and quickSortIterative, along with a driver code to test the sorting process.

The partition function is used for the process of partitioning a given subarray into two parts – elements less than or equal to the chosen pivot (arr[h]) on the left and elements greater on the right. It operates within the range defined by indices l and h. The function scans through the subarray and rearranges elements based on their relationship to the pivot, ensuring that the pivot eventually reaches its correct sorted position. The function returns the index where the pivot is placed.

The quickSortIterative function performs the iterative Quicksort algorithm. It operates by utilizing a stack to manage the subarrays that need to be sorted. The stack keeps track of subarray ranges through pairs of indices (l, h). The function initializes the stack and pushes the initial range of the entire array onto it. It then enters a loop where it repeatedly pops subarray ranges from the stack, applies the partition function to find the pivot’s position, and pushes subarray ranges onto the stack for further processing. This loop continues until the stack becomes empty, indicating that all subarrays have been sorted.

Finally, the driver code initializes an array arr with unsorted elements. It calculates the length of the array (n) and then calls the quickSortIterative function to sort the entire array. The sorted array is printed as the final output.

In summary, the code demonstrates the iterative implementation of the Quicksort algorithm, which utilizes a stack to manage subarray sorting and partitioning efficiently. This approach eliminates the need for recursive function calls, making it suitable for scenarios where recursion might lead to issues like stack overflow.

Python




# Python program for implementation of Quicksort
 
# This function is same in both iterative and recursive
def partition(arr,l,h):
    i = ( l - 1 )
    x = arr[h]
 
    for j in range(l , h):
        if arr[j] <= x:
 
            # increment index of smaller element
            i = i+1
            arr[i],arr[j] = arr[j],arr[i]
 
    arr[i+1],arr[h] = arr[h],arr[i+1]
    return (i+1)
 
# Function to do Quick sort
# arr[] --> Array to be sorted,
# l --> Starting index,
# h --> Ending index
def quickSortIterative(arr,l,h):
 
    # Create an auxiliary stack
    size = h - l + 1
    stack = [0] * (size)
 
    # initialize top of stack
    top = -1
 
    # push initial values of l and h to stack
    top = top + 1
    stack[top] = l
    top = top + 1
    stack[top] = h
 
    # Keep popping from stack while is not empty
    while top >= 0:
 
        # Pop h and l
        h = stack[top]
        top = top - 1
        l = stack[top]
        top = top - 1
 
        # Set pivot element at its correct position in
        # sorted array
        p = partition( arr, l, h )
 
        # If there are elements on left side of pivot,
        # then push left side to stack
        if p-1 > l:
            top = top + 1
            stack[top] = l
            top = top + 1
            stack[top] = p - 1
 
        # If there are elements on right side of pivot,
        # then push right side to stack
        if p+1 < h:
            top = top + 1
            stack[top] = p + 1
            top = top + 1
            stack[top] = h
 
# Driver code to test above
arr = [4, 3, 5, 2, 1, 3, 2, 3]
n = len(arr)
quickSortIterative(arr, 0, n-1)
print ("Sorted array is:")
for i in range(n):
    print ("%d" %arr[i]),
 
# This code is contributed by Mohit Kumra


Output:

Sorted array is:
1 2 2 3 3 3 4 5

Time Complexity: O(n*log(n))
Auxiliary Space: O(n)

The above mentioned optimizations for recursive quick sort can also be applied to iterative version. 1) Partition process is same in both recursive and iterative. The same techniques to choose optimal pivot can also be applied to iterative version. 2) To reduce the stack size, first push the indexes of smaller half. 3) Use insertion sort when the size reduces below a experimentally calculated threshold. Please refer complete article on Iterative Quick Sort for more details!



Last Updated : 28 Aug, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads