Key Takeaways: Quick Sort is one of the fastest and most widely used sorting algorithms. It works by choosing a "pivot" element and moving all smaller elements to its left and larger elements to its right. It uses a "Divide and Conquer" strategy.
Bubble Sort and Selection Sort are very slow for large datasets. If you have millions of items, you need a faster algorithm.
Quick Sort is exactly that. It is heavily used in real-world software because of its incredible speed.
Quick Sort uses a strategy called Divide and Conquer.
Instead of trying to sort the whole array at once, it breaks the array into smaller, easier-to-sort pieces. It solves the small pieces, and by doing so, the whole array becomes sorted!
Quick Sort relies on a core concept called Partitioning.
Here is the step-by-step process:
Partitioning: The pivot (4) moves to the middle. Smaller items go left. Larger items go right.
Because the left and right halves keep getting split into smaller and smaller arrays, the sorting happens incredibly fast.
Let's sort this array: [8, 2, 5, 3, 9, 4]
Step 1: First Partition
4.2, 3) to the left of 4.8, 5, 9) to the right of 4.[2, 3, 4, 8, 5, 9].Step 2: Sort the Left Side
[2, 3].3. 2 is smaller, so it stays on the left.Step 3: Sort the Right Side
[8, 5, 9].9. Both 8 and 5 are smaller, so they go to the left.[8, 5, 9]. The 9 is permanently sorted.[8, 5]. Pivot is 5. The 8 is larger, so it goes to the right.[5, 8].Final Result: [2, 3, 4, 5, 8, 9]. The whole array is sorted!
Here is a beginner-friendly Python implementation. Notice how the function calls itself (which is called Recursion).
def quick_sort(arr): # A single item (or empty array) is already sorted! if len(arr) <= 1: return arr # 1. Pick the pivot (we choose the last element) pivot = arr[-1] # 2. Create arrays for smaller and larger elements smaller = [] larger = [] # 3. Partition the data for i in range(len(arr) - 1): if arr[i] < pivot: smaller.append(arr[i]) else: larger.append(arr[i]) # 4. Recursively sort the left and right, then combine! return quick_sort(smaller) + [pivot] + quick_sort(larger)numbers = [8, 2, 5, 3, 9, 4] print("Original:", numbers) print("Sorted:", quick_sort(numbers))
O(n log n). By constantly splitting the array in half, the algorithm runs incredibly efficiently. This is why it is preferred for large data.O(n²). If the array is already sorted and you always pick the last element as the pivot, it degrades into a slow algorithm. (Advanced versions of Quick Sort pick a random pivot to avoid this).What happens to the "pivot" element after the partitioning step?