Quick Sort

Algorithms

Quick sort is a divide-and-conquer algorithm that picks a pivot element and partitions the array around the pivot, placing smaller elements before it and larger elements after it.

Algorithm

The quick sort algorithm follows these steps:

  1. Pick a pivot element from the array
  2. Partition the array: elements less than pivot go left, elements greater go right
  3. Recursively apply quick sort to the left and right partitions

Time Complexity

Implementation

def quick_sort(arr):
    if len(arr) <= 1:
        return arr
    else:
        # Choose a pivot element
        pivot = arr[len(arr) // 2]
        # Partitioning step
        left = [x for x in arr if x < pivot]
        middle = [x for x in arr if x == pivot]
        right = [x for x in arr if x > pivot]
        # Recursively apply quick_sort to the partitions
        return quick_sort(left) + middle + quick_sort(right)

# Example usage with different numbers
arr = [45, 23, 78, 12, 56, 89, 34]
sorted_arr = quick_sort(arr)
print("Sorted array:", sorted_arr)

Trace it by hand

ProblemLomuto partition with the last element as pivot
Run a single Lomuto partition on [3, 6, 1, 8, 2, 9, 4, 7, 5]. The pivot is the last element (5). After partition, all elements ≤ 5 should be to the left and all > 5 to the right, with 5 itself at the boundary. What's the array after partition, and at what index does the pivot end up?