Python Program for Iterative Quick Sort
Quicksort is one of the most efficient sorting algorithms and is commonly implemented using recursion. However, recursion can cause stack overflow errors when dealing with very large datasets. To overcome this, we can use an iterative version of Quicksort that replaces recursive calls with an explicit stack to manage subarrays.
How It Works
- The algorithm divides the array into smaller parts based on a pivot element.
- Elements smaller than or equal to the pivot go to its left, and greater elements go to its right.
- Instead of recursive calls, a stack is used to keep track of subarrays that still need sorting.
- Each time a range is taken from the stack, the partition function places the pivot at its correct position, and new subarray ranges are pushed onto the stack.
- The process continues until the stack is empty - meaning the entire array is sorted.
Python Code Implementation
1. Partition Function: This function places the pivot element at its correct sorted position.
def partition(arr, l, h):
i = l - 1
pivot = arr[h]
for j in range(l, h):
if arr[j] <= pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i]
arr[i + 1], arr[h] = arr[h], arr[i + 1]
return i + 1
2. Iterative QuickSort Function: This function uses a stack instead of recursion.
def quickSortIterative(arr, l, h):
size = h - l + 1
stack = [0] * size
top = -1
top += 1
stack[top] = l
top += 1
stack[top] = h
while top >= 0:
h = stack[top]
top -= 1
l = stack[top]
top -= 1
p = partition(arr, l, h)
if p - 1 > l:
top += 1
stack[top] = l
top += 1
stack[top] = p - 1
if p + 1 < h:
top += 1
stack[top] = p + 1
top += 1
stack[top] = h
3. Driver Code
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(arr[i], end=" ")
Output:
Sorted array is:
1 2 2 3 3 3 4 5
Complete Code:
def partition(arr, l, h):
i = l - 1
pivot = arr[h]
for j in range(l, h):
if arr[j] <= pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i]
arr[i + 1], arr[h] = arr[h], arr[i + 1]
return i + 1
def quickSortIterative(arr, l, h):
size = h - l + 1
stack = [0] * size
top = -1
top += 1
stack[top] = l
top += 1
stack[top] = h
while top >= 0:
h = stack[top]
top -= 1
l = stack[top]
top -= 1
p = partition(arr, l, h)
if p - 1 > l:
top += 1
stack[top] = l
top += 1
stack[top] = p - 1
if p + 1 < h:
top += 1
stack[top] = p + 1
top += 1
stack[top] = h
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(arr[i], end=" ")
Output
Sorted array is: 1 2 2 3 3 3 4 5
Explanation:
- partition(): selects the last element as pivot and places it at its correct position while rearranging other elements around it.
- quickSortIterative(): manages the sorting process using a stack to store subarray ranges that need sorting.
- The loop continues until the stack is empty, meaning all subarrays are sorted.