10 Sorting Algorithms Compared: Which Is Best and Fastest (with Code)

10 Sorting Algorithms Compared: Which Is Best and Fastest (with Code)

Short answer: there is no single best sorting algorithm. For everyday code, use your language's built-in sort (Timsort in Python, a quicksort or Timsort variant in Java, usually introsort in C++). It is faster and better tested than anything you will write by hand. For interviews, know insertion sort, merge sort, quick sort and heap sort well, and know when counting sort or radix sort can beat O(n log n).

The table below gives you the full comparison. After that, each algorithm gets a plain explanation, a worked example, Python code you can run, and its complexity with the reason behind it.

Sorting algorithms comparison table

n is the number of items. k is the range of values (max − min + 1). d is the number of digits and b is the base (10 for decimal digits).

AlgorithmBestAverageWorstExtra spaceStable?In-place?Use it when
Bubble sortO(n)O(n²)O(n²)O(1)YesYesTeaching, or a tiny list that is almost sorted
Selection sortO(n²)O(n²)O(n²)O(1)NoYesWrites are costly (it makes at most n − 1 swaps)
Insertion sortO(n)O(n²)O(n²)O(1)YesYesSmall arrays or nearly sorted data
Shell sortO(n log n)Depends on the gap sequenceO(n²) with n/2, n/4 … gapsO(1)NoYesMedium arrays, short code, no recursion
Merge sortO(n log n)O(n log n)O(n log n)O(n)YesNoYou need stability or a guaranteed O(n log n); linked lists; huge files
Quick sortO(n log n)O(n log n)O(n²)O(log n) stack on averageNoYesGeneral in-memory arrays; usually fastest on random data
Heap sortO(n log n)O(n log n)O(n log n)O(1)NoYesGuaranteed O(n log n) with no extra memory
Counting sortO(n + k)O(n + k)O(n + k)O(n + k)YesNoIntegers in a small range (marks, ages, ratings)
Radix sort (LSD)O(d·(n + b))O(d·(n + b))O(d·(n + b))O(n + b)YesNoMany fixed-length integer keys (IDs, phone numbers)
Bucket sortO(n + k)O(n + k) for evenly spread dataO(n²)O(n + k)Yes, if each bucket uses a stable sortNoFloats spread evenly over a known range

Three terms from the table, in plain words:

  • Stable means two items with equal keys stay in the order they arrived. Sort students by marks with a stable sort and two students with 82 keep their original (say, alphabetical) order.
  • In-place means the algorithm rearranges the array it was given and needs only a small, fixed amount of extra memory.
  • Comparison sort vs non-comparison sort. The first seven algorithms only ask "is a smaller than b?". Counting, radix and bucket sort use the value itself (as an index or a digit), which is how they get under O(n log n).

If big-O notation is new to you, read Time Complexity Simplified with Easy Examples first.

Every Python function in this post was run on empty lists, one-item lists, lists with duplicates, reverse-sorted lists and 300 random lists each, and checked against Python's own sorted().

1. Bubble Sort

The idea: walk through the list and swap any two neighbours that are in the wrong order. After the first pass, the largest item has "bubbled" to the end. Repeat on the rest. If a full pass makes no swap, the list is sorted and you can stop.

Worked example on [5, 3, 8, 4, 2]:

pass 1: [3, 5, 4, 2, 8]   8 bubbles to the end
pass 2: [3, 4, 2, 5, 8]   5 is in place
pass 3: [3, 2, 4, 5, 8]
pass 4: [2, 3, 4, 5, 8]   sorted
def bubble_sort(arr):
    n = len(arr)
    for i in range(n - 1):
        swapped = False
        for j in range(n - 1 - i):          # the last i items are already in place
            if arr[j] > arr[j + 1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
                swapped = True
        if not swapped:                     # no swaps means the list is sorted
            break
    return arr

Complexity: O(n²) average and worst, because there are up to n − 1 passes of up to n − 1 comparisons each. Best case O(n), because on an already sorted list the first pass makes no swap and the loop stops. Extra space O(1).

2. Selection Sort

The idea: find the smallest item in the unsorted part and swap it to the front. The sorted part grows by one item each round.

Worked example on [5, 3, 8, 4, 2]:

i=0: smallest of the rest is 2 -> [2, 3, 8, 4, 5]
i=1: smallest of the rest is 3 -> [2, 3, 8, 4, 5]   (already in place)
i=2: smallest of the rest is 4 -> [2, 3, 4, 8, 5]
i=3: smallest of the rest is 5 -> [2, 3, 4, 5, 8]
def selection_sort(arr):
    n = len(arr)
    for i in range(n - 1):
        smallest = i
        for j in range(i + 1, n):
            if arr[j] < arr[smallest]:
                smallest = j
        arr[i], arr[smallest] = arr[smallest], arr[i]
    return arr

Complexity: O(n²) in every case, because finding the minimum always scans the whole unsorted part, sorted input or not (n(n − 1)/2 comparisons). Extra space O(1). It is not stable: the long-distance swap can jump an item over an equal one. Its one strength is that it does at most n − 1 swaps.

3. Insertion Sort

The idea: the way most people sort playing cards in their hand. Take the next item, shift the bigger items in the sorted part one step right, and drop the item into the gap.

Worked example on [5, 3, 8, 4, 2]:

insert 3: [3, 5, 8, 4, 2]
insert 8: [3, 5, 8, 4, 2]   8 is already bigger than everything before it
insert 4: [3, 4, 5, 8, 2]
insert 2: [2, 3, 4, 5, 8]
def insertion_sort(arr):
    for i in range(1, len(arr)):
        current = arr[i]
        j = i - 1
        while j >= 0 and arr[j] > current:  # shift bigger items one step right
            arr[j + 1] = arr[j]
            j -= 1
        arr[j + 1] = current
    return arr

Complexity: O(n²) average and worst, because each new item may shift past everything before it (reverse-sorted input is the worst case). Best case O(n), because on sorted input each item needs one comparison and no shifts. Extra space O(1), and it is stable.

This is the most useful of the simple sorts. Real library sorts switch to insertion sort for short runs because it has very little overhead. More on it in Master Insertion Sort Before Your Next Big Interview.

4. Shell Sort

The idea: insertion sort is slow when an item is far from its final place, because it moves one step at a time. Shell sort first runs insertion sort on items that are gap positions apart, so items can jump long distances early. The gap shrinks each round. The last round has gap 1, which is plain insertion sort on an array that is now almost sorted.

Worked example on [9, 8, 7, 6, 5, 4, 3, 2] (8 items, so gaps 4, 2, 1):

gap 4: [5, 4, 3, 2, 9, 8, 7, 6]   pairs 4 apart are sorted
gap 2: [3, 2, 5, 4, 7, 6, 9, 8]   items 2 apart are sorted
gap 1: [2, 3, 4, 5, 6, 7, 8, 9]   one cheap insertion-sort pass finishes it
def shell_sort(arr):
    n = len(arr)
    gap = n // 2
    while gap > 0:
        for i in range(gap, n):             # insertion sort on items gap apart
            current = arr[i]
            j = i
            while j >= gap and arr[j - gap] > current:
                arr[j] = arr[j - gap]
                j -= gap
            arr[j] = current
        gap //= 2
    return arr

Complexity: with the simple n/2, n/4 … gaps used here, the worst case is O(n²). Better gap sequences do better: Knuth's 1, 4, 13, 40 … gives O(n^1.5) in the worst case. Best case is O(n log n), because sorted input costs about n comparisons per round and there are about log n rounds. Extra space O(1). Not stable.

5. Merge Sort

The idea: divide and conquer. Split the list in half, sort each half (by the same method), then merge the two sorted halves by repeatedly taking the smaller front item.

Worked example on [5, 3, 8, 4, 2]. The list splits into [5, 3] and [8, 4, 2], and keeps splitting down to single items. Then the merges run bottom-up:

merge [5] + [3]          -> [3, 5]
merge [4] + [2]          -> [2, 4]
merge [8] + [2, 4]       -> [2, 4, 8]
merge [3, 5] + [2, 4, 8] -> [2, 3, 4, 5, 8]
def merge_sort(arr):
    if len(arr) <= 1:
        return arr
    mid = len(arr) // 2
    left = merge_sort(arr[:mid])
    right = merge_sort(arr[mid:])
    return merge(left, right)


def merge(left, right):
    result = []
    i = j = 0
    while i < len(left) and j < len(right):
        if left[i] <= right[j]:             # <= keeps equal items in order (stable)
            result.append(left[i])
            i += 1
        else:
            result.append(right[j])
            j += 1
    result.extend(left[i:])
    result.extend(right[j:])
    return result

Note that this version returns a new list instead of changing the one you pass in.

Complexity: O(n log n) in every case, because halving gives about log₂ n levels and merging every level touches all n items. Extra space O(n) for the merged lists. Stable, thanks to the <=.

Merge sort is the natural choice for linked lists (merging only re-links nodes) and for data too large for memory: sort chunks that fit in RAM, write them to disk, then merge the chunks. Deep dive: Everything You Need To Know About Merge Sort.

6. Quick Sort

The idea: pick one item as the pivot. Partition the array so everything smaller than the pivot sits to its left and everything else to its right. The pivot is now in its final position. Repeat on the left part and the right part.

The code below takes the middle item as the pivot, moves it to the end, and uses the Lomuto partition scheme.

Worked example on [5, 3, 8, 4, 2]:

range 0..4, pivot 8: [5, 3, 2, 4, 8]   8 lands at index 4 (an unlucky pivot: nothing to its right)
range 0..3, pivot 3: [2, 3, 5, 4, 8]   3 lands at index 1
range 2..3, pivot 5: [2, 3, 4, 5, 8]   5 lands at index 3, done
def quick_sort(arr, low=0, high=None):
    if high is None:
        high = len(arr) - 1
    if low < high:
        p = partition(arr, low, high)
        quick_sort(arr, low, p - 1)
        quick_sort(arr, p + 1, high)
    return arr


def partition(arr, low, high):
    mid = (low + high) // 2
    arr[mid], arr[high] = arr[high], arr[mid]   # use the middle item as pivot
    pivot = arr[high]
    i = low                                     # next slot for a "small" item
    for j in range(low, high):
        if arr[j] < pivot:
            arr[i], arr[j] = arr[j], arr[i]
            i += 1
    arr[i], arr[high] = arr[high], arr[i]       # pivot goes to its final place
    return i

Complexity: O(n log n) on average, because a typical pivot splits the array into two reasonably sized parts, giving about log n levels of O(n) partitioning work. Worst case O(n²), when the pivot is the smallest or largest item every time, so each level removes only one item. Extra space is the recursion stack: O(log n) on average, O(n) in the worst case. Not stable.

The catch: this simple version also goes quadratic when many items are equal. In our tests, an array of 1,000 identical values took 499,500 comparisons, and the recursion went about 1,000 calls deep, so under Python's default recursion limit (1,000) that input stops with a RecursionError. Production quicksorts fix this with three-way partitioning (a separate "equal to pivot" zone), better pivot choice, and a fallback to heap sort when recursion gets too deep. More on it in The Complete Quick Sort Guide.

7. Heap Sort

The idea: arrange the array as a max-heap, a binary tree stored inside the array where every parent is at least as big as its children (the children of index i are at 2i + 1 and 2i + 2). The largest item is then at index 0. Swap it to the end, shrink the heap by one, and repair the heap by sifting the new root down. Repeat.

Worked example on [5, 3, 8, 4, 2]:

max-heap built:    [8, 4, 5, 3, 2]
move 8 to index 4: [5, 4, 2, 3, 8]
move 5 to index 3: [4, 3, 2, 5, 8]
move 4 to index 2: [3, 2, 4, 5, 8]
move 3 to index 1: [2, 3, 4, 5, 8]
def heap_sort(arr):
    n = len(arr)
    for start in range(n // 2 - 1, -1, -1):     # build a max-heap
        sift_down(arr, start, n)
    for end in range(n - 1, 0, -1):
        arr[0], arr[end] = arr[end], arr[0]     # move the max to the end
        sift_down(arr, 0, end)                  # repair the smaller heap
    return arr


def sift_down(arr, root, size):
    while True:
        largest = root
        left, right = 2 * root + 1, 2 * root + 2
        if left < size and arr[left] > arr[largest]:
            largest = left
        if right < size and arr[right] > arr[largest]:
            largest = right
        if largest == root:
            return
        arr[root], arr[largest] = arr[largest], arr[root]
        root = largest

Complexity: O(n log n) in the best, average and worst case, because building the heap takes O(n) and each of the n removals sifts down a tree of height about log₂ n. (If every key is equal, the sift stops at once and it runs in O(n).) Extra space O(1). Not stable.

Heap sort gives you merge sort's worst-case guarantee without merge sort's extra memory. It is often slower than quick sort in practice because it jumps around the array, which uses the CPU cache poorly.

8. Counting Sort

The idea: don't compare at all. Count how many times each value appears, turn the counts into end positions with a running total (prefix sums), then place each item straight into its slot. Walking the input backwards while placing keeps equal items in their original order.

Worked example on [4, 2, 2, 8, 3, 3, 1] (values 1 to 8):

counts for values 1..8 = [1, 2, 2, 1, 0, 0, 0, 1]
prefix sums            = [1, 3, 5, 6, 6, 6, 6, 7]   e.g. the 3s end at position 5
output                 = [1, 2, 2, 3, 3, 4, 8]
def counting_sort(arr):
    if not arr:
        return arr
    low, high = min(arr), max(arr)
    count = [0] * (high - low + 1)
    for x in arr:
        count[x - low] += 1
    for v in range(1, len(count)):              # prefix sums: last position of each value
        count[v] += count[v - 1]
    output = [0] * len(arr)
    for x in reversed(arr):                     # walk backwards to stay stable
        count[x - low] -= 1
        output[count[x - low]] = x
    return output

Subtracting low lets this version handle negative integers too.

Complexity: O(n + k) time and O(n + k) space in every case, because it makes a fixed number of passes over the n items and over the k possible values. Stable.

The catch: k matters. Sorting exam marks out of 100 is ideal (k = 101). Sorting 5,000 numbers that range up to 1,000,000 means building and scanning a million counters, and in our test it was roughly 15 times slower than radix sort on the same data (see the timing table below).

9. Radix Sort

The idea: sort the numbers one digit at a time, starting from the last digit (least significant digit, or LSD). Each digit pass uses a stable counting sort on that digit, so the order from earlier passes is kept for ties.

Worked example on [170, 45, 75, 90, 802, 24, 2, 66]:

by ones digit:     [170, 90, 802, 2, 24, 45, 75, 66]
by tens digit:     [802, 2, 24, 45, 66, 170, 75, 90]
by hundreds digit: [2, 24, 45, 66, 75, 90, 170, 802]
def radix_sort(arr):
    if not arr:
        return arr
    exp = 1
    while max(arr) // exp > 0:
        arr = counting_sort_by_digit(arr, exp)
        exp *= 10
    return arr


def counting_sort_by_digit(arr, exp):
    count = [0] * 10
    for x in arr:
        count[(x // exp) % 10] += 1
    for d in range(1, 10):
        count[d] += count[d - 1]
    output = [0] * len(arr)
    for x in reversed(arr):
        d = (x // exp) % 10
        count[d] -= 1
        output[count[d]] = x
    return output

This version handles non-negative integers. For negatives, sort them separately (by absolute value, then reverse) and put them in front.

Complexity: O(d·(n + b)), because there are d digit passes and each is a counting sort over n items and b = 10 possible digits. Extra space O(n + b). Stable. When d is small and fixed (say, 10-digit phone numbers), this is linear in n.

10. Bucket Sort

The idea: spread the values into a row of buckets by their size, sort each small bucket, then join the buckets in order. It works best when values are spread evenly, so each bucket gets only a few items.

Worked example on [0.42, 0.32, 0.23, 0.52, 0.25, 0.47, 0.51] with 7 buckets from the minimum (0.23) to the maximum (0.52):

bucket 0: [0.23, 0.25]
bucket 1: [0.32]
bucket 2: []
bucket 3: [0.42]
bucket 4: [0.47]
bucket 5: [0.51]
bucket 6: [0.52]
joined:   [0.23, 0.25, 0.32, 0.42, 0.47, 0.51, 0.52]
def bucket_sort(arr):
    n = len(arr)
    if n <= 1:
        return arr
    low, high = min(arr), max(arr)
    if low == high:
        return arr
    buckets = [[] for _ in range(n)]
    for x in arr:
        index = int((x - low) / (high - low) * (n - 1))
        buckets[index].append(x)
    result = []
    for b in buckets:
        result.extend(insertion_sort(b))
    return result

It reuses insertion_sort from section 3 for each bucket.

Complexity: O(n + k) on average for evenly spread data (k is the number of buckets, n here), because each bucket holds only a few items and sorting them is cheap. Worst case O(n²), when almost everything lands in one bucket and insertion sort has to do all the work. Extra space O(n + k). Stable, because items enter each bucket in input order and insertion sort is stable.

Bonus: Comb Sort

The idea: bubble sort with a gap. Compare items gap apart instead of neighbours, and shrink the gap by a factor of 1.3 each pass. Small values stuck near the end (the reason bubble sort is slow) move forward quickly. Once the gap reaches 1, it keeps doing bubble passes until one makes no swap.

Worked example on [8, 4, 1, 56, 3, -44, 23, -6, 28, 0]:

gap 7: [-6, 4, 0, 56, 3, -44, 23, 8, 28, 1]
gap 5: [-44, 4, 0, 28, 1, -6, 23, 8, 56, 3]
gap 3: [-44, 1, -6, 23, 4, 0, 3, 8, 56, 28]
gap 2: [-44, 1, -6, 0, 3, 8, 4, 23, 56, 28]
gap 1: [-44, -6, 0, 1, 3, 4, 8, 23, 28, 56]
gap 1: no swaps, done
def comb_sort(arr):
    gap = len(arr)
    swapped = True
    while gap > 1 or swapped:
        gap = max(1, int(gap / 1.3))            # shrink the gap by 1.3 each pass
        swapped = False
        for i in range(len(arr) - gap):
            if arr[i] > arr[i + gap]:
                arr[i], arr[i + gap] = arr[i + gap], arr[i]
                swapped = True
    return arr

Complexity: worst case O(n²), because the final gap-1 phase is bubble sort and can still need many passes in bad cases. Best case O(n log n), because sorted input needs about log₁.₃ n passes of O(n) each. On random data it is far faster than bubble sort. Extra space O(1). Not stable.

Which sorting algorithm is fastest?

It depends on the data, but the honest ranking looks like this:

  1. Any comparison sort needs about n log₂ n comparisons in the worst case. That is a proven lower bound, so merge sort, heap sort and quick sort (on average) are already as good as comparison sorting gets in big-O terms.
  2. Among those, quick sort variants are usually fastest on random in-memory arrays. Partitioning works on one contiguous block of memory and does little bookkeeping per step.
  3. On data that is already partly sorted, adaptive sorts win. Timsort finds existing sorted runs and merges them, so nearly sorted input costs close to O(n).
  4. For small integer keys, counting sort and radix sort beat O(n log n) because they never compare items.

To make this concrete, we timed the pure-Python functions from this post on 5,000 random integers between 0 and 1,000,000, and on a nearly sorted copy (sorted, then 50 random pairs swapped). This is one run on one laptop (Python 3.12.8, Apple Silicon Mac, best of 3, 18 Nov 2026), so read it as a rough ranking, not a spec.

AlgorithmRandom (ms)Nearly sorted (ms)
Bubble sort782457
Selection sort320323
Insertion sort31610
Shell sort7.24.3
Comb sort7.06.2
Merge sort6.04.8
Quick sort3.93.3
Heap sort6.76.9
Counting sort6565
Radix sort4.13.9
Bucket sort1.71.5
Python's built-in sorted()0.40.1

What the numbers show:

  • The three O(n²) sorts are about 40 to 200 times slower than the O(n log n) ones at only 5,000 items, and that gap widens as n grows.
  • Insertion sort drops from 316 ms to 10 ms on nearly sorted data. Selection sort does not change at all.
  • Bucket sort wins among our functions because this data is evenly spread, which is exactly its best case.
  • Counting sort is slow here because k (a million possible values) is 200 times bigger than n.
  • The built-in sorted() is about 4 times faster than our best function and about 10 times faster than our quick sort. It is written in C and adapts to existing order. This is the real lesson: in production, call the library.

Which sorting algorithm to use in interviews vs production

In interviews

Unless the question is "implement a sort", call the built-in sort and state its cost: O(n log n) time. Then be ready for follow-ups that test whether you understand the algorithms underneath:

  • Insertion sort: the answer for "small or nearly sorted input".
  • Merge sort: stability, linked lists, counting inversions, external sorting.
  • Quick sort: the partition step, which also powers quickselect (k-th smallest item in O(n) average) and the Dutch national flag problem.
  • Heap sort and heaps: top-k problems and merging k sorted lists.
  • Counting sort: when the input range is small and known (ages, marks, characters).

In production

Use the standard library. Here is what the main languages actually do, according to their official documentation:

  • Python: list.sort() and sorted() use Timsort, a stable hybrid of merge sort and insertion sort that takes advantage of any order already present. Since Python 3.11 it decides which runs to merge using the Powersort strategy (CPython changelog, listsort.txt).
  • Java, primitive arrays: Arrays.sort(int[]) uses a Dual-Pivot Quicksort by Vladimir Yaroslavskiy, Jon Bentley and Joshua Bloch, which the Java documentation says offers O(n log n) performance on all data sets. Stability does not matter here, because two equal ints cannot be told apart.
  • Java, objects: Arrays.sort(Object[]), List.sort() and Collections.sort() use a stable, adaptive, iterative mergesort adapted from Python's Timsort (Arrays.sort(Object[]), List.sort).
  • C++: std::sort must make O(N log N) comparisons and is not stable (cppreference). The standard does not name an algorithm, but implementations usually use introsort: quicksort that switches to heap sort if recursion gets too deep and finishes small ranges with insertion sort. GCC's libstdc++ does exactly this (__introsort_loop in stl_algo.h). Use std::stable_sort when you need stability.
  • JavaScript: Array.prototype.sort has been required to be stable since ECMAScript 2019 (ECMA-262, 10th edition). V8, the engine in Chrome and Node.js, has used Timsort since V8 v7.0 (V8 blog).

Here is the same task in all four languages: sort numbers, then sort students by marks with a stable sort so Asha (who came first) stays ahead of Meera.

nums = [5, 3, 8, 4, 2]
print(sorted(nums))          # new list: [2, 3, 4, 5, 8]
nums.sort(reverse=True)      # in place
print(nums)                  # [8, 5, 4, 3, 2]

students = [("Asha", 82), ("Ravi", 91), ("Meera", 82), ("Kiran", 75)]
students.sort(key=lambda s: s[1])   # stable: Asha stays before Meera
print(students)

Output:

[2, 3, 4, 5, 8]
[8, 5, 4, 3, 2]
[('Kiran', 75), ('Asha', 82), ('Meera', 82), ('Ravi', 91)]
import java.util.*;

public class LibrarySort {
    record Student(String name, int marks) {}

    public static void main(String[] args) {
        int[] nums = {5, 3, 8, 4, 2};
        Arrays.sort(nums);                       // primitives: Dual-Pivot Quicksort
        System.out.println(Arrays.toString(nums));

        List<Student> students = new ArrayList<>(List.of(
            new Student("Asha", 82), new Student("Ravi", 91),
            new Student("Meera", 82), new Student("Kiran", 75)));
        students.sort(Comparator.comparingInt(Student::marks)); // objects: stable TimSort
        System.out.println(students);
    }
}

Output (Java 16 or later, because of record):

[2, 3, 4, 5, 8]
[Student[name=Kiran, marks=75], Student[name=Asha, marks=82], Student[name=Meera, marks=82], Student[name=Ravi, marks=91]]
#include <algorithm>
#include <iostream>
#include <string>
#include <utility>
#include <vector>

int main() {
    std::vector<int> nums = {5, 3, 8, 4, 2};
    std::sort(nums.begin(), nums.end());          // introsort in GCC's libstdc++
    for (int x : nums) std::cout << x << ' ';
    std::cout << '\n';

    std::vector<std::pair<std::string, int>> students = {
        {"Asha", 82}, {"Ravi", 91}, {"Meera", 82}, {"Kiran", 75}};
    std::stable_sort(students.begin(), students.end(),   // keeps Asha before Meera
                     [](const auto& a, const auto& b) { return a.second < b.second; });
    for (const auto& s : students) std::cout << s.first << ':' << s.second << ' ';
    std::cout << '\n';
}

Output (compile with C++14 or later):

2 3 4 5 8
Kiran:75 Asha:82 Meera:82 Ravi:91
const nums = [5, 3, 8, 4, 2, 10];
console.log([...nums].sort());                 // [10, 2, 3, 4, 5, 8]  compares as strings!
console.log([...nums].sort((a, b) => a - b));  // [2, 3, 4, 5, 8, 10]

const students = [["Asha", 82], ["Ravi", 91], ["Meera", 82], ["Kiran", 75]];
students.sort((a, b) => a[1] - b[1]);          // stable since ES2019
console.log(students.map(s => s.join(":")).join(" "));

Output in Node.js:

[ 10, 2, 3, 4, 5, 8 ]
[ 2, 3, 4, 5, 8, 10 ]
Kiran:75 Asha:82 Meera:82 Ravi:91

That first JavaScript line is a classic bug: without a compare function, sort() converts numbers to strings, so "10" comes before "2".

Common sorting interview questions

1. What is a stable sort, and when does it matter? A stable sort keeps equal items in their original order. It matters when you sort by one key after another: sort orders by time, then stable-sort by customer, and each customer's orders stay in time order.

2. Why is quick sort usually preferred for arrays and merge sort for linked lists? Quick sort works in place on contiguous memory and is fast on average. Merge sort on a linked list needs no extra array (merging just re-links nodes), while quick sort's usual tricks (picking the middle or a random item as pivot, swapping items by index) need fast random access that linked lists don't have.

3. Can a comparison sort ever beat O(n log n)? Not in the worst case. There are n! possible orderings, and each comparison has two outcomes, so you need at least log₂(n!) comparisons to tell them apart, which grows like n log n. Counting and radix sort get around this by not comparing.

4. How do you avoid quick sort's O(n²) worst case? Pick the pivot randomly or as the median of three items, use three-way partitioning when there are many duplicates, and fall back to heap sort if recursion gets too deep (that last trick is introsort).

5. How do you find the k-th largest element without fully sorting? Quickselect: partition once, then recurse only into the side that contains position k. Average O(n). Or keep a min-heap of size k while scanning the array: O(n log k).

6. How do you sort an array of only 0s, 1s and 2s in one pass? Dutch national flag partitioning with three pointers (low, mid, high). Swap 0s to the front and 2s to the back as mid walks the array. O(n) time, O(1) space. Counting sort with three counters also works in two passes.

7. How would you sort a 100 GB file on a machine with 8 GB of RAM? External merge sort. Read chunks that fit in memory, sort each one, and write it to disk as a sorted run. Then merge all runs together with a min-heap that holds the current front item of each run.

8. How do you count inversions in an array? An inversion is a pair i < j with a[i] > a[j]. Modify merge sort: whenever you take an item from the right half during a merge, every item still waiting in the left half forms an inversion with it. O(n log n).

9. Which simple sort makes the fewest swaps? Selection sort, with at most n − 1 swaps. That is useful only when writing to memory is much more expensive than reading.

Want to check yourself? Try the Crio sorting quiz.

FAQ

Which is the best sorting algorithm?

There is no single best one. For general use, your language's built-in sort (Timsort, dual-pivot quicksort or introsort) is the best choice. Among classic algorithms, merge sort is best when you need stability, heap sort when memory is tight, quick sort for speed on random arrays, and counting sort for small integer ranges.

What is the fastest sorting algorithm?

On random data in memory, well-tuned quicksort variants are usually fastest among comparison sorts. On partly sorted data, Timsort is often faster because it reuses existing runs. When keys are small integers, counting sort or radix sort can beat both because they run in linear time instead of O(n log n).

Which is the easiest sorting algorithm to learn?

Bubble sort is the easiest to understand: swap neighbours until nothing is out of order. Insertion sort is just as short, and it is far more useful in practice because it runs in O(n) time on nearly sorted data. Learn both first, then move on to merge sort and quick sort.

How many sorting algorithms are there?

There is no fixed count. Dozens have been published, including many variants and hybrids of the classics. For interviews and everyday work, about ten matter: the ten covered in this post. Most production sorts, like Timsort and introsort, are hybrids built from merge sort, quick sort, heap sort and insertion sort.

Which sorting algorithm does Python use?

Python's list.sort() and sorted() use Timsort, a stable hybrid of merge sort and insertion sort. It finds runs that are already in order and merges them, so nearly sorted lists sort in close to linear time. Since Python 3.11, it chooses its merge order using the Powersort strategy.

Is quick sort better than merge sort?

For in-memory arrays, quick sort is usually faster and needs only O(log n) stack space on average, but its worst case is O(n²) and it is not stable. Merge sort always runs in O(n log n) and is stable, but needs O(n) extra memory. Pick merge sort for stability, linked lists or huge files.

Keep going

Sorting is where most people first see divide and conquer, recursion and time-space trade-offs working together. Next, read how sorted data unlocks binary search, then practise the top data structures interview questions.

If you want to use these ideas while building real backend systems, with mentors reviewing your code, look at Crio's Software Development Fellowship Program. It covers data structures and algorithms alongside backend and full-stack projects, so you practise problem-solving in the same kind of code you would write at work.

Sandipan Das

Written by Sandipan Das

Trying to bring about a difference through words.
You've successfully subscribed to Crio Blog
Great! Next, complete checkout to get full access to all premium content.
Welcome back! You've successfully signed in.
Unable to sign you in. Please try again.
Success! Your account is fully activated, you now have access to all content.
Error! Stripe checkout failed.
Success! Your billing info is updated.
Billing info update failed.