Skip to content
TeachTrails
DSAAlgorithms

Sorting Algorithms Explained: Visualization & Time Complexity

Sorting algorithms explained with a live visualizer: bubble, selection, insertion, merge and quick sort, a time complexity table, merge sort code and a memory trick.

Sudipta Biswas, AI Engineer

11 min read

Beginner friendly
unsortedsortedBubble · Selection · Insertion · Merge · Quick

Sorting algorithms are the classic DSA topic: they appear in every exam, every interview prep list and every “learn to code” course. Sorting itself is easy to understand: put things in order. The magic is in how each algorithm does it, and why some are dramatically faster than others.

This guide explains the five sorting algorithms every student should know, with a live visualizer, a full time complexity table, merge sort code in Python, Java and C++, and a memory trick for all five.

Sorting algorithm visualizer

Pick an algorithm and press Play. Then try the same data with a different algorithm and compare the counters.

📊 Sorting algorithm visualizer

Data:
39
comparisons
19
swaps
65
steps

Step 1/65: Bubble sort: compare neighbours and swap if they're in the wrong order. The biggest value bubbles to the end each pass.

comparingmovingpivotin place

Tip: run each algorithm on “Nearly sorted”, then “Reversed”, and compare the comparison counts.

The 5 sorting algorithms explained

1. Bubble sort: biggest bubbles to the top

Walk through the array comparing neighbours and swap them if they're out of order. After each pass, the largest remaining value has “bubbled” to the end. Simple, but O(n²). With an early-exit check it's O(n) on already-sorted data.

2. Selection sort: the team captain

Like a captain picking players, scan the unsorted part, select the smallest, and swap it to the front. Always O(n²) comparisons, but it makes very few swaps.

3. Insertion sort: cards in your hand

Take the next item and insert it into its correct place among the already-sorted items to its left, exactly how you sort playing cards. O(n²) in general, but very fast for small or nearly sorted arrays.

4. Merge sort: split the deck, merge the piles

Split the array in half again and again until each piece has one item, then merge pieces back together in order. It takes log n levels of splitting with n work per level: O(n log n) every time. It's stable but needs O(n) extra memory.

5. Quick sort: the class monitor (pivot)

Pick a pivot, like a class monitor, and line everyone up: smaller values to its left, bigger to its right. The pivot is now in its final place; repeat on each side. O(n log n) on average and usually the fastest in practice, but O(n²) if the pivots are consistently bad (for example, always picking the last item of already-sorted data).

Time complexity of all sorting algorithms

AlgorithmBestAverageWorstExtra spaceStable?
Bubble sortO(n)O(n²)O(n²)O(1)Yes
Selection sortO(n²)O(n²)O(n²)O(1)No
Insertion sortO(n)O(n²)O(n²)O(1)Yes
Merge sortO(n log n)O(n log n)O(n log n)O(n)Yes
Quick sortO(n log n)O(n log n)O(n²)O(log n)No
Heap sortO(n log n)O(n log n)O(n log n)O(1)No

Not sure what O(n²) and O(n log n) really mean? See Big O notation explained, which includes a growth graph.

🧠 PATH memory card

Remember the 5 sorting algorithms for good

Picture it · Anchor it · Trace it · Hit-recall it. Four quick steps that turn “I read it once” into “I can explain it in an exam”.

  1. P

    Picture it

    Your brain remembers scenes far better than definitions.

    Bubblesbubble sort👆Captainselection sortCardsinsertion sortSplit deckmerge sortMonitorquick sort

    ← swipe to see the whole picture →

    Five everyday scenes: bubbles rising, a team captain picking the smallest player, sorting cards in your hand, splitting a deck between friends then merging piles, and a class monitor lining students up shorter-left, taller-right.

  2. A

    Anchor it

    A silly sentence you can't forget, where every word maps to the concept.

    “Bubbles, Captains, Cards crawl; Split and Monitor fly”

    • Bubbles→Bubble sort: biggest floats to the end. O(n²)
    • Captains→Selection sort: pick the smallest each round. O(n²)
    • Cards→Insertion sort: slide each card into place. O(n²), great if nearly sorted
    • crawl→These three are the slow O(n²) group
    • Split→Merge sort: split in halves, merge back. Always O(n log n), stable
    • Monitor fly→Quick sort: pivot puts smaller left, bigger right. O(n log n) average
  3. T

    Trace it

    Run it by hand on a tiny example once. Doing beats reading.

    Insertion-sort [5, 2, 4, 1] by hand: pick 2 → [2, 5, 4, 1]; pick 4 → [2, 4, 5, 1]; pick 1 → [1, 2, 4, 5]. Then run the same array in the visualizer with Bubble and Merge and compare the comparison counts.
  4. H

    Hit-recall it

    Test yourself now, then again on the day each card comes back.

    Card 1 / 8 · new0 mastered · 0 practised

    Say the answer out loud first, then flip and be honest.

Merge sort code (Python, Java, C++)

Merge sort is the most common “write a sorting algorithm” exam and interview question, because it shows recursion and divide and conquer clearly.

Merge sort
def merge_sort(arr):
    if len(arr) <= 1:
        return arr
    mid = len(arr) // 2
    left = merge_sort(arr[:mid])     # sort each half
    right = merge_sort(arr[mid:])
    return merge(left, right)        # then merge them

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

print(merge_sort([38, 12, 55, 7, 44, 23]))  # [7, 12, 23, 38, 44, 55]

How to choose a sorting algorithm

  • Small or nearly sorted data: insertion sort.
  • Need guaranteed O(n log n) and stability: merge sort.
  • Fast in-memory sorting on average: quick sort (with a good pivot choice).
  • Little extra memory and guaranteed O(n log n): heap sort.
  • Learning or teaching: bubble and selection sort, because they're easy to trace by hand.

What to learn next

Once data is sorted, you can search it in O(log n) with binary search. And for the two most common data structures in DSA, read stack vs queue.

Key takeaways

  • Bubble, selection and insertion sort are simple but O(n²).
  • Merge sort is always O(n log n) and stable, but uses O(n) extra memory.
  • Quick sort is O(n log n) on average and fast in practice, but O(n²) in the worst case.
  • Insertion sort shines on small or nearly sorted data.
  • Remember all five with “Bubbles, Captains, Cards crawl; Split and Monitor fly.”

Frequently asked questions

Which sorting algorithm is the fastest?

There is no single fastest for every case. For general-purpose sorting, O(n log n) algorithms like merge sort, quick sort and heap sort are the standard choices; quick sort is often fastest in practice on average. For small or nearly sorted arrays, insertion sort can beat them. Real libraries usually combine algorithms, such as Timsort or introsort.

What is the time complexity of all sorting algorithms?

Bubble, selection and insertion sort are O(n²) on average and in the worst case. Merge sort and heap sort are O(n log n) in all cases. Quick sort is O(n log n) on average but O(n²) in the worst case. Bubble and insertion sort can be O(n) on already-sorted data.

What is a stable sorting algorithm?

A sort is stable if items with equal keys keep their original relative order. For example, if two students both scored 80, a stable sort keeps them in the order they were listed. Merge, insertion and bubble sort are stable; quick, selection and heap sort usually are not.

What is the difference between merge sort and quick sort?

Both use divide and conquer. Merge sort splits the array in half, sorts each half and merges them; it is always O(n log n) and stable but needs O(n) extra memory. Quick sort partitions around a pivot and sorts each side in place; it is usually faster in practice but can degrade to O(n²) with bad pivots.

Which sorting algorithm does Python or Java use?

Python's sorted() and list.sort() use Timsort, a hybrid of merge sort and insertion sort. Java uses a dual-pivot quick sort for arrays of primitives and Timsort for objects. Both are O(n log n) in the worst case for objects.

🧠 Quick check: sorting algorithms

  1. 1. Which of these has O(n log n) time in the worst case?

  2. 2. Which algorithm works like sorting playing cards in your hand?

  3. 3. Your data is almost sorted already. Which simple sort is fast here?

  4. 4. In the anchor “Bubbles, Captains, Cards crawl; Split and Monitor fly”, what is the Monitor?

DSA for Beginners

Part 4 of 4: Sorting Algorithms Explained