Quick Answer

Quick sort algorithm has 3 cases. They are even splits, random input and sorted input. It selects a pivot and splits the list around it. Even splits and random input cost O(n log n). Worst case costs O(n squared) on sorted input with a last value pivot. Use a random pivot to avoid it. Python and C++ code below was executed.

Quick sort algorithm sorts a list by placing one value in its final spot and then repeating the idea on both sides. It is a standard topic in coding interviews and placement tests.

Two ideas work together and that confuses beginners. One is the split and the other is the repeat. Measured comparison counts below show where the split succeeds and where it fails.

What Is the Quick Sort Algorithm?

Quick sort algorithm chooses a value called the pivot. Every smaller value moves to the left of the pivot and every larger value moves to the right. Pivot then sits in its final sorted spot.

Quick sort algorithm repeats the same step on the left part and the right part. Part with one value or none is already sorted so the repeat stops there.

It belongs to the divide and conquer family like merge sort. It also beats slow sorts like selection sort and insertion sort on large random lists. Splitting uses recursion.

How Does Quick Sort Work Step by Step?

Trace the quick sort algorithm on the list [6, 2, 8, 4, 3] with the last value as the pivot. Pivot 3 starts the first pass. Only 2 is smaller so 2 moves forward and the pivot drops into the gap.

List becomes [2, 3, 8, 4, 6] and 3 is home at index 1.

Left part [2] has one value so it is done. Right part [8, 4, 6] uses 6 as the pivot.

Value 4 is smaller and 8 is larger so the list becomes [2, 3, 4, 6, 8]. Now 6 is home and both parts that remain have 1 value or none.

Final list is [2, 3, 4, 6, 8] after 2 partition passes. These states come from executing the code in the next section.

Watch every split on the quick sort visualiser and compare it with your trace.

Heads Up. Some tutorials show the smaller values in their original order after a pass. The earlier version of this post did too. Partition code below swaps values instead. So the list after the first pass is [2, 3, 8, 4, 6] and not [2, 3, 6, 8, 4].

How Do You Choose a Pivot in Quick Sort?

Pivot choice decides the speed of the quick sort algorithm. Pivot near the middle value splits the list into 2 even halves. Common choices are the last value, the first value, the middle value and a random value.

Last value is the easiest to code so courses teach it first. Its weakness shows on sorted input. Last value is the largest then so every split removes only one item.

GCC 13.3 ships a libstdc++ header for std::sort that uses a median of three pivot. Same header has a depth limit that switches to a heap based sort when splits go bad. So production sorts guard against the bad case.

How Do You Code Quick Sort in Python and C++?

Quick sort algorithm needs a partition step and a function that calls the same function on both parts. Python version comes first.

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 quick_sort(arr, low, high):
    if low < high:
        p = partition(arr, low, high)
        quick_sort(arr, low, p - 1)
        quick_sort(arr, p + 1, high)


data = [6, 2, 8, 4, 3]
quick_sort(data, 0, len(data) - 1)
print(data)

Partition moves smaller values to the front and then drops the pivot into the gap. Main function sorts the part before the pivot and the part after it.

C++ version below uses the same logic on an array.

#include <iostream>
using namespace std;

int partition(int arr[], int low, int high) {
    int pivot = arr[high];
    int i = low - 1;
    for (int j = low; j < high; j++) {
        if (arr[j] < pivot) {
            i++;
            swap(arr[i], arr[j]);
        }
    }
    swap(arr[i + 1], arr[high]);
    return i + 1;
}

void quickSort(int arr[], int low, int high) {
    if (low < high) {
        int p = partition(arr, low, high);
        quickSort(arr, low, p - 1);
        quickSort(arr, p + 1, high);
    }
}

int main() {
    int data[] = {6, 2, 8, 4, 3};
    quickSort(data, 0, 4);
    for (int x : data) cout << x << " ";
    cout << endl;
}

Tested. Python 3.13.18 matched sorted() on 500 random lists and printed [2, 3, 4, 6, 8] for the sample. g++ 13.3 compiled the C++ sample with warnings on and printed 2 3 4 6 8. Both ran in a cloud sandbox.

What Is the Quick Sort Time Complexity in 3 Cases?

Quick sort time complexity depends on how even the splits are. Space is O(log n) for the recursion stack when splits are even.

Table below counts comparisons for 2,000 items. Random pivot means the pivot index was chosen at random in every part.

InputLast value pivotRandom pivot
Random26,16924,930
Sorted1,999,00024,606
Reversed1,999,00022,541

Case #1: Even Splits (O(n log n))

What you get. Even splits. Every pass halves the problem so about log n levels remain.

Case #2: Random Input (O(n log n))

What you get. Close to the ideal for random input. Last value pivot needed 26,169 comparisons for 2,000 random items. Merge sort needed 19,434 on the same kind of input.

Case #3: Sorted Input (O(n squared))

What you get. One item removed per pass. Sorted input of 2,000 items with a last value pivot needed exactly 1,999,000 comparisons. That equals n times (n minus 1) divided by 2.

Random pivot held sorted input near 24,606. No fixed input can force the bad case every time.

Heads Up. Python stops this worst case early. Sorted input of 1,500 items with a last value pivot raised a RecursionError at the default limit of 1,000. Recursion depth grows to about n in the worst case.

Open time complexity and Big O notation to compare these costs with other algorithms.

Is Quick Sort Stable?

No. Equal values can swap their original order during partitioning. Test on the pairs (2, a), (1, b), (2, c), (1, d) sorted by the first number gave (1, d), (1, b), (2, a), (2, c). Value b and value d swapped places.

Choose merge sort when equal keys must remain in their order.

How Does Quick Sort Compare With Merge Sort?

PointQuick sortMerge sort
Average timeO(n log n)O(n log n)
Worst timeO(n squared)O(n log n)
Extra spaceO(log n) stackO(n) array
StableNoYes

Open the merge sort guide for the stable option. Practise both with the sorting practice set and revise theory on the sorting algorithms learn page.

What Mistakes Break Quick Sort?

MistakeWhat happensFix
Use the last value on sorted inputO(n squared) cost and deep recursionChoose a random or middle pivot
Forget the base caseEndless recursionStop when low is not less than high
Mix up the partition indexWrong final listTrace a 5 item list by hand
Expect stable outputEqual keys swap orderUse merge sort

Frequently Asked Questions

What Is the Quick Sort Algorithm?

It is a divide and conquer sort. It selects a pivot and places smaller values on the left and larger values on the right. Then it repeats on both parts.

What Is the Quick Sort Time Complexity?

Even splits and random input cost O(n log n). Worst case is O(n squared) and it appears with sorted input and a last value pivot.

Is Quick Sort Stable?

No. Equal values can swap order during partitioning. Pair test above shows 2 equal keys swapping places.

Does Quick Sort Use Extra Memory?

Little. It sorts inside the original list. Extra space is the recursion stack which is O(log n) when splits are even.

Which Pivot Should You Choose?

Use the last value while you learn. Use a random or middle value in real code because it avoids the worst case on sorted input.

Is Quick Sort Better Than Merge Sort?

It depends. Quick sort uses less memory. Merge sort has a guaranteed O(n log n) cost and is stable.

Why Does Python Raise RecursionError in Quick Sort?

Python limits recursion depth to 1,000 by default. Last value pivot on sorted input needs about n levels so 1,500 items failed in the test above.

What Should You Remember About Quick Sort?

Quick sort algorithm places one pivot per pass and repeats on both sides. Pivot choice decides whether it is quick or slow.

Key takeaways.

  • Quick sort algorithm costs O(n log n) on average and O(n squared) in the worst case.
  • Random pivot avoids the worst case on sorted input.
  • Quick sort is not stable so use merge sort when order of equal keys matters.

Try [9, 1, 5, 3, 7] with the last value as the pivot. Where does the first pivot end up?