~/coding-interview/quick-sort-algorithm.md

Quick Sort Algorithm

2 min readMay 19, 2019by Gorav Singal#coding-interview#sorting-algorithms#quick-sort
// TL;DR

Choose a pivot, partition array into elements ≤ pivot and > pivot, recurse on both halves. O(n log n) average, O(n²) worst case. In-place and cache-friendly.

Quick Sort Algorithm

This algorithm is very useful for large input. And, is quite efficient one. It has several implementation, and it is proved that for practical cases, it is better than Merge Sort, Heap Sort any many other algorithms. Although, its worst complexity is O(n^2).

This is again an implementation of of Divide and Conquer algorithms. In this algorithm, we first find a pivot element, put it in a position such that every element in left is less than or equal than this. And every element on right side is greater than equal than this number.

So, this pivot element divides the array into two parts. Then, natural recursive algorithm work on individual smaller arrays. Note: It is very important to choose correct pivot element. This algorithm works best when pivot element divides the array into almost equal halves. That is the reason, there are several implementations are available for selecting pivot element.

In a simple implementation, we simply choose the last element as pivot. Some algorithms choose a random pivot element.

Quick Sort Algorithm

  • First, we call partition on the array, where lies the main logic of putting the pivot element to correct position.
  • Pivot element divides the array into two partitions.
  • Now, runs the recursive method on the two partitions.
  • Ultimately, partition sorts the sub-array.

See the code here:

public static int partition(int[] arr, int l, int r) {
    int p = r;  //pivot
    
    int sm = l;
    for (int i=l; i<r; i++) {
        if (arr[i] < arr[p]) {
            ArrayUtils.swap(arr, i, sm);
            sm++;
        }
    }
    ArrayUtils.swap(arr, sm, p);
    return sm;
}

public static void qsort(int[] arr, int l, int r) {
    if (l < r) {
        int p = partition(arr, l, r);
        
        qsort(arr, l, p-1);
        qsort(arr, p+1, r);
    }
}

The main logic resides in partition() method. We just kept an index variable: sm which keeps track of all smaller number than our pivot element. And, finally swap our index sm and pivot element index.

Graphical Example

Quick Sort Example

Quick Sort Example

Key Points

  • It does not use extra memory.
  • Very efficient in sorting large number set.
  • Practically best performer than merge sort, if implemented better for selecting pivot element.
  • Performance is very good. Average complexity is O(n log n)
  • Based on Divice and Conquer technique
  • It works well in virtual memory environment

Runtime complexity

The average runtime is O(n log n), but worst case is O(n^2)

$ subscribe --weekly

One deep dive a week, in your inbox

System design, AI engineering, trading systems and interview prep. Tested code, real numbers. Free, and you can unsubscribe any time.

or read it on gyanbyte.substack.com

Share

Related Posts

Radix Sort Algorithm

Radix Sort Algorithm

A number consists of digits. Example: 843. Its a 3-digit number. Radix sort…

Counting Sort Algorithm

Counting Sort Algorithm

Counting sort runs on relatively smaller set of input. Counting sort calculates…

Heap Sort Algorithm

Heap Sort Algorithm

This is another very useful sorting algorithm based on Heap data structure. Read…

Merge Sort Algorithm

Merge Sort Algorithm

This algorithm is very efficient one, and is classic example of Divide and…

Bubble Sort Algorithm

Bubble Sort Algorithm

This is kind of preliminary technique of sorting. And, this is the first…

Selection Sort Algorithm

Selection Sort Algorithm

It is one of a simple algorithm to study for a beginner to understanding sorting…

Latest Posts

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

In the previous article I argued that AI is not killing software engineering…

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

A few months back I approved a PR that was almost entirely AI-generated. It…

How to Debug AI-Generated Code: Understand First, Fix Last

How to Debug AI-Generated Code: Understand First, Fix Last

In the last article I wrote about reviewing AI code before it goes in. This one…

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

Every few weeks somebody sends me a scary headline — “AI will replace all…

The Transactional Outbox Pattern: Never Lose an Event Again

The Transactional Outbox Pattern: Never Lose an Event Again

This is one of those patterns that looks like nothing until you get burnt once…

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Here is a question I like to ask in interviews: your bank account shows a…