Skip to content
GATEiit

GATE DA · Programming, Data Structures and Algorithms

Basic sorting algorithms: selection sort, bubble sort and insertion sort

Selection, bubble and insertion sort: how each pass works, exact counts of comparisons and swaps, inversions, best and worst cases, stability, and tracing the array after k passes.

Before you start

  • Python loops and lists →

    The algorithms are nested loops over list indices, often given as Python code.

  • Arithmetic series

    Comparison counts add up as (n−1)+(n−2)+⋯+1=n(n−1)/2.

This topic comes before: Divide and conquer: merge sort and quicksort, Search algorithms: linear search and binary search

Concept notes

1. Selection sort

In pass i (starting at 0), selection sort finds the minimum of a[i..n-1] and swaps it into position i. After pass i the first i+1 items are the smallest ones, in final order.

def selection_sort(a):
    n = len(a)
    for i in range(n - 1):
        m = i
        for j in range(i + 1, n):
            if a[j] < a[m]:
                m = j
        a[i], a[m] = a[m], a[i]
  • Comparisons: always (n−1)+(n−2)+⋯+1=n(n−1)2, whatever the input. So best, average and worst case are all Θ(n2).
  • Swaps: at most n−1, one per pass. This is the fewest swaps of the three algorithms, which matters when writes are costly.
  • In-place: O(1) extra space.
  • Not stable: the long-distance swap can jump an item over an equal one. For [2a, 2b, 1] the first pass swaps 2a and 1, giving [1, 2b, 2a].
  • Not adaptive: a sorted input still costs n(n−1)/2 comparisons.

Selection sort can also be written to select the maximum and place it at the end; check which version the question uses.

2. Bubble sort

Bubble sort compares adjacent pairs from left to right and swaps them when out of order. Each pass carries the largest remaining item to the end, so after pass k the last k positions are final.

def bubble_sort(a):
    n = len(a)
    for p in range(n - 1):
        swapped = False
        for j in range(n - 1 - p):
            if a[j] > a[j + 1]:
                a[j], a[j + 1] = a[j + 1], a[j]
                swapped = True
        if not swapped:
            break
  • Comparisons: pass p makes n−1−p comparisons; all n−1 passes make n(n−1)2.
  • Swaps: each adjacent swap removes exactly one inversion, so the total number of swaps equals the number of inversions.
  • Early exit: with the swapped flag, an already sorted array needs one pass of n−1 comparisons: best case O(n). Without the flag it is always Θ(n2).
  • Stable (equal items are never swapped, because the test is >), and in-place.

Small items move left only one place per pass ("turtles"), so an array like [2, 3, 4, 5, 1] needs all n−1 passes.

Start514283Pass 1142538Pass 2124358Pass 3123458Thick boxes: largest items already in their final place
Bubble sort on [5, 1, 4, 2, 8, 3]: sorted after pass 3; a 4th pass with no swaps stops the flagged version

3. Insertion sort

Insertion sort keeps a[0..i-1] sorted and inserts a[i] into it by shifting larger items one place right.

def insertion_sort(a):
    for i in range(1, len(a)):
        key = a[i]
        j = i - 1
        while j >= 0 and a[j] > key:
            a[j + 1] = a[j]
            j -= 1
        a[j + 1] = key
  • Shifts: each shift fixes one inversion, so total shifts = number of inversions I.
  • Comparisons: between I and I+n−1. Each insertion that stops before reaching the front makes one extra failing comparison.
  • Best case (sorted input): n−1 comparisons, 0 shifts, Θ(n). Worst case (reverse sorted): n(n−1)2 comparisons and shifts, Θ(n2). Average Θ(n2).
  • Stable (it stops at an equal item because the test is >), in-place, adaptive (fast on nearly sorted data) and online (can sort items as they arrive).

After pass i the first i+1 items are sorted among themselves, but unlike selection sort they are not necessarily in their final positions.

Using binary search to find the insertion point cuts comparisons to O(nlog⁡n), but the shifts keep the time at O(n2).

4. Inversions and the comparison table

An inversion is a pair of positions i<j with a[i]>a[j]. A sorted array has 0 inversions; a reverse-sorted array has the maximum n(n−1)2. A random permutation has n(n−1)4 on average.

To count by hand, for each item count the smaller items to its right and add.

Selection Bubble (with flag) Insertion
Best time Θ(n2) Θ(n) Θ(n)
Worst time Θ(n2) Θ(n2) Θ(n2)
Swaps / shifts ≤n−1 =I =I
Stable No Yes Yes
In-place Yes Yes Yes
Adaptive No Yes Yes

Why Ω(n2) for adjacent swaps: any algorithm that only swaps neighbours removes one inversion per swap, so on reverse-sorted input it needs n(n−1)/2 swaps.

Which to use: insertion sort for small or nearly sorted inputs (it is used inside faster sorts for small pieces); selection sort when swaps or writes are expensive; bubble sort mainly as a teaching tool. All three are beaten by O(nlog⁡n) sorts for large n.

Formulas to remember

Comparisons in selection sort (and bubble sort without flag)
n(n−1)2
Maximum inversionsReverse-sorted array
Imax⁡=(n2)=n(n−1)2
Average inversions of a random permutation
n(n−1)4
Insertion sort comparisons
I≤C≤I+n−1
Bubble sort swaps
swaps=I

Common mistakes

  • Assuming selection sort is faster on sorted input; it always makes n(n−1)/2 comparisons.
  • Thinking the first k items after k insertion sort passes are in final position; they are only sorted among themselves.
  • Counting bubble sort passes without the final no-swap pass that the flag needs.
  • Calling selection sort stable; the swap can reorder equal keys.
  • Equating insertion sort comparisons with inversions; add one for each insertion that stops before the front.

Worked examples

Try each step yourself, then reveal the working.

Example 1: Tracing selection sort

numerical

Sort [29, 10, 14, 37, 13] with selection sort (select the minimum). Show the array after each pass and count the swaps that actually move items.

  1. Step 1: Pass 0: find the minimum of the whole array.

    Try it on paper first.

Example 2: Bubble sort passes

numerical

Apply bubble sort with the early-exit flag to [5, 1, 4, 2, 8, 3]. How many passes run, and how many swaps are made?

  1. Step 1: Run pass 1.

    Try it on paper first.

Example 3: Insertion sort shifts and comparisons

numerical

Sort [6, 2, 8, 1, 5, 3] with insertion sort. Find the number of shifts and the number of comparisons a[j] > key.

  1. Step 1: Count inversions to get the shifts.

    Try it on paper first.

Example 4: Which sort is stable?

conceptual

Records (2, a), (2, b), (1, c) are sorted by the number. Which of selection, bubble and insertion sort keep (2, a) before (2, b)?

  1. Step 1: Run selection sort.

    Try it on paper first.

Previous year questions

4 official GATE DA questions on this topic, newest first.

Practise these 4 PYQs →

Topic test

10 questions: up to 4 official PYQs and original practice questions, with GATE marking (MCQ wrong answers lose marks). Score 60% or more to pass. A new set is drawn each time.

Mark as mastered

Loading your progress…

My revision notes

Notes written by the GATEiit team against the official GATE DA syllabus; being checked by a reviewer. Updated 2026-11-21. Spotted a mistake? Use Report an issue on any question, or contact us.