CS205

Quick Sort

O(n log n)

Picks a pivot element and partitions the array around it.

Quick Sort
64
34
25
12
22
11
90
0
1
2
3
4
5
6
Ready to start
Step 0 of 0
Speed:500ms
Default
Comparing
Swapping
Sorted
Pivot
Algorithm Info

Picks a pivot element and partitions the array around it.

Best Case
O(n log n)
Average Case
O(n log n)
Worst Case
O(n²)
Space
O(log n)
How It Works
  1. Choose a pivot element (commonly last, first, or median)
  2. Partition: rearrange array so elements smaller than pivot are on left, larger on right
  3. The pivot is now in its final sorted position
  4. Recursively apply quicksort to left and right subarrays
  5. Base case: subarrays with 0 or 1 elements are sorted
Pseudocode
quickSort(arr, low, high):
    if low < high:
        pivotIndex = partition(arr, low, high)
        quickSort(arr, low, pivotIndex - 1)
        quickSort(arr, pivotIndex + 1, high)

partition(arr, low, high):
    pivot = arr[high]
    i = low - 1
    for j = low to high - 1:
        if arr[j] < pivot:
            i++
            swap(arr[i], arr[j])
    swap(arr[i+1], arr[high])
    return i + 1
Complexity Analysis
Time Complexity
Best:O(n log n)
Average:O(n log n)
Worst:O(n²)
Space Complexity
O(log n)
Stable Sort?
No
Advantages & Disadvantages
Advantages
  • Very fast in practice - often faster than merge sort
  • In-place sorting - O(log n) stack space
  • Good cache performance due to locality
  • Can be parallelized for better performance
  • Works well with virtual memory
Disadvantages
  • Worst case O(n^2) for already sorted or reverse sorted
  • Not stable - may change order of equal elements
  • Performance depends heavily on pivot selection
  • Recursive - can cause stack overflow for very large arrays
When to Use Quick Sort
  • General purpose sorting in many standard libraries
  • When average case performance matters most
  • Memory-constrained environments
  • When stability is not required
  • Arrays with random data