Python Program for QuickSort

QuickSort is a divide-and-conquer sorting algorithm that works by selecting a pivot element and partitioning the array around it. Elements smaller than the pivot go to the left, and larger elements go to the right.

How QuickSort Works

The algorithm follows these steps ?

Step 1: Choose Pivot 5 2 8 3 7 (Pivot: 7) Step 2: Partition Left ? pivot 5 2 3 7 Right > pivot 8 Step 3: Recursively Sort Partitions Sort left Pivot Sort right Result: Sorted Array 2 3 5 7 8

Implementation

Partition Function

This function rearranges the array so elements smaller than the pivot come before it ?

def partition(arr, low, high):
    # Choose the rightmost element as pivot
    pivot = arr[high]
    i = low - 1  # Index of smaller element
    
    for j in range(low, high):
        # If current element is smaller than or equal to pivot
        if arr[j] <= pivot:
            i += 1
            arr[i], arr[j] = arr[j], arr[i]  # Swap elements
    
    # Place pivot in correct position
    arr[i + 1], arr[high] = arr[high], arr[i + 1]
    return i + 1  # Return pivot index

QuickSort Function

This function recursively sorts the partitions ?

def quicksort(arr, low, high):
    if low < high:
        # Partition the array and get pivot index
        pi = partition(arr, low, high)
        
        # Recursively sort elements before and after partition
        quicksort(arr, low, pi - 1)    # Sort left partition
        quicksort(arr, pi + 1, high)   # Sort right partition

Complete Example

def partition(arr, low, high):
    pivot = arr[high]
    i = low - 1
    
    for j in range(low, high):
        if arr[j] <= pivot:
            i += 1
            arr[i], arr[j] = arr[j], arr[i]
    
    arr[i + 1], arr[high] = arr[high], arr[i + 1]
    return i + 1

def quicksort(arr, low, high):
    if low < high:
        pi = partition(arr, low, high)
        quicksort(arr, low, pi - 1)
        quicksort(arr, pi + 1, high)

# Test the implementation
numbers = [2, 5, 3, 8, 6, 5, 4, 7]
print("Original array:", numbers)

quicksort(numbers, 0, len(numbers) - 1)
print("Sorted array:", numbers)
Original array: [2, 5, 3, 8, 6, 5, 4, 7]
Sorted array: [2, 3, 4, 5, 5, 6, 7, 8]

Time Complexity

Case Time Complexity When?
Best O(n log n) Pivot divides array evenly
Average O(n log n) Random pivot selection
Worst O(n²) Already sorted array

Key Points

? In-place sorting: Requires only O(log n) extra space for recursion
? Unstable: Does not preserve relative order of equal elements
? Divide-and-conquer: Breaks problem into smaller subproblems

Conclusion

QuickSort is an efficient sorting algorithm that uses partitioning to divide the array around a pivot element. It has average-case O(n log n) performance and is widely used due to its in-place sorting capability and good cache performance.

Updated on: 2026-03-25T06:51:32+05:30

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements