AlgorithmsIntermediate

Quick Sort in Python

Learn Quick Sort in Python! A beginner-friendly guide to the famous Divide and Conquer algorithm. See how pivots and partitioning make sorting blazing fast.

Try it yourself

Run this code directly in your browser. Click "Open in full editor" to experiment further.

Loading...

Click Run to see output

Or press Ctrl + Enter

How it works

Quick Sort is arguably the most famous sorting algorithm in the world! Like Merge Sort, it uses the incredibly smart Divide and Conquer strategy, but in a totally different and super memory-efficient way.

How It Works (The Pivot Strategy)

Imagine you have a messy line of kids sorted randomly by height.

1. Pick a Pivot: You just point to one random kid (let's say the last kid in line) and say, "You are the Pivot!"

2. Partitioning (The Magic Step): You tell everyone shorter than the Pivot to stand on their left, and everyone taller than the Pivot to stand on their right.

3. Boom! The Pivot kid is now standing in their exact, permanent, perfectly sorted spot in the final line! They never have to move again.

4. Recursion: Now you just repeat this exact same process for the messy subgroup on the left, and the messy subgroup on the right.

Time and Space Complexity

  • Time Complexity: O(n log n) on average. It's blazing fast! BUT... if you are really unlucky and you accidentally pick the tallest or shortest kid as the pivot every single time, it can slow down to O(n^2).
  • Space Complexity: Wait, why is it so famous? Because our quick_sort_inplace version requires almost zero extra memory (O(log n) for the recursion stack)! Since we just swap kids around inside the original line without making new lines, it's incredibly memory-efficient compared to Merge Sort space-wise!
  • Why is it so popular?

    Because it does all the sorting in-place (right inside the original array), it's incredibly friendly to your computer's CPU cache. In the real world, the standard Quick Sort often runs significantly faster than Merge Sort!

    Related examples

    Keywords: python quick sort, quick sort python, quick sort implementation python, python sorting algorithms, divide and conquer python, in-place sort python