Skip to lesson

Bubble, selection and insertion sort

Bubble sort, selection sort, and insertion sort are elementary quadratic sorting algorithms. Each illustrates a fundamental strategy for arranging data in place.

Bubble sort: repeated adjacent swaps

Bubble sort compares neighbours and swaps them when they are out of order, so the largest value moves to the end on every pass. The program below sorts five numbers this way.

  1. Outer loop runs from 0 to n - 1.
  2. Initialize swapped boolean flag to false.
  3. Inner loop compares array[j] with array[j+1] up to n - i - 1.
  4. If array[j] > array[j+1], swap them and set swapped to true.
  5. If swapped remains false after inner loop, break early.

Example 1 · Bubble Sort with Early Exit Optimization

BubbleSortDemo.javaJava
import java.util.Arrays;
public class BubbleSortDemo {    public static void bubbleSort(int[] nums) {        int n = nums.length;        for (int i = 0; i < n - 1; i++) {            boolean swapped = false;            for (int j = 0; j < n - i - 1; j++) {                if (nums[j] > nums[j + 1]) {                    int tmp = nums[j];                    nums[j] = nums[j + 1];                    nums[j + 1] = tmp;                    swapped = true;                }            }            if (!swapped) break;        }    }
    public static void main(String[] args) {        int[] arr = {5, 1, 4, 2, 8};        bubbleSort(arr);        System.out.println(Arrays.toString(arr));    }}
Output
[1, 2, 4, 5, 8]

What this code does

  • Inner loop bubbles largest elements toward the array tail.
  • swapped flag detects early completion if array is sorted.
  • Result is sorted in place in O(n²) time.

In each pass, the largest remaining unsorted element bubbles up to its final position at the end. Why is pure bubble sort slow? Every comparison that finds inverted neighbors requires a swap, performing up to O(n²) swaps and comparisons. An early-exit boolean flag stops the algorithm if a pass completes without making any swaps. Consider tracing bubble sort on array [5, 1, 4, 2]: Pass 1 compares (5, 1) and swaps: [1, 5, 4, 2]. Next, compare (5, 4) and swaps: [1, 4, 5, 2]. Next, compare (5, 2) and swaps: [1, 4, 2, 5]. Value 5 is now placed at the end! Pass 2 compares (1, 4) (no swap), then compares (4, 2) and swaps: [1, 2, 4, 5]. Value 4 is placed. Pass 3 makes no swaps, so early-exit terminates the algorithm cleanly. Edge cases include arrays that are already sorted, which bubble sort detects in O(n) time using the flag. Reverse-sorted arrays represent the absolute worst case, requiring n * (n - 1) / 2 swaps.

  • Bubble mechanism: repeatedly swap adjacent out-of-order pairs.
  • Early exit optimization: terminate immediately if a full pass makes zero swaps.
  • Time complexity: O(n) best case when sorted, O(n²) average and worst case.

Predict the output

Predict one bubble pass

Read each snippet and pick what it prints.

Round 1 of 2

int[] a = {5, 1, 4, 2};
for (int j = 0; j < 3; j++) {
if (a[j] > a[j + 1]) {
int t = a[j]; a[j] = a[j + 1]; a[j + 1] = t;
}
}
System.out.println(Arrays.toString(a));

Selection sort: selecting the minimum element

Selection sort finds the smallest unsorted value on each pass and swaps it to the front, using at most one swap per pass. The program below sorts five numbers this way.

Example 2 · Selection Sort with Minimal Swaps

SelectionSortDemo.javaJava
import java.util.Arrays;
public class SelectionSortDemo {    public static void selectionSort(int[] nums) {        int n = nums.length;        for (int i = 0; i < n - 1; i++) {            int minIdx = i;            for (int j = i + 1; j < n; j++) {                if (nums[j] < nums[minIdx]) {                    minIdx = j;                }            }            if (minIdx != i) {                int tmp = nums[i];                nums[i] = nums[minIdx];                nums[minIdx] = tmp;            }        }    }
    public static void main(String[] args) {        int[] arr = {64, 25, 12, 22, 11};        selectionSort(arr);        System.out.println(Arrays.toString(arr));    }}
Output
[11, 12, 22, 25, 64]

What this code does

  • Each outer loop pass finds the index of the minimum element in suffix.
  • At most one swap is executed per pass.
  • Total swaps across the entire execution never exceed n - 1.

In each pass, it scans the unsorted suffix for the minimum value. Then it swaps with the first unsorted slot. Why does selection sort use fewer swaps? It performs at most one swap per pass. Total swaps never exceed n - 1 across the entire sort. However, it always scans all remaining elements, making O(n²) comparisons even on already sorted arrays. Consider tracing selection sort on array [5, 1, 4, 2]: Pass 0 finds minimum in [5, 1, 4, 2]: min is 1 at index 1. Swap with index 0: [1, 5, 4, 2]. Pass 1 finds minimum in suffix [5, 4, 2]: min is 2 at index 3. Swap with index 1: [1, 2, 4, 5]. Pass 2 finds minimum in suffix [4, 5]: min is 4 at index 2. It is already in place: [1, 2, 4, 5]. After 3 passes, the entire array is sorted. A crucial property of selection sort is that it is inherently unstable. For example, sorting [2a, 2b, 1] swaps 2a with 1. This places 2a after 2b, disrupting relative order.

  • Selection strategy: scan unsorted range for minimum element and swap to front.
  • Swap efficiency: strictly bounded by n - 1 swaps, useful when writes are expensive.
  • Unstable behavior: long-distance swaps can reorder identical keys.

Order of execution

One selection pass

Tap the steps of one pass in order.

Insertion sort and its unique practical strengths

Insertion sort takes one value at a time and slides it left into its place among the values already sorted. The program below sorts five numbers this way.

Insertion sort: insert 2 into [1, 4, 5]

Step 1 of 5

Array: 1, 4, 5, 2. key at index 3.
key
2
The first three values 1, 4, 5 are already in order. The next value to insert is key = 2 (index 3).

Example 3 · Insertion Sort with In-Place Shifts

InsertionSortDemo.javaJava
import java.util.Arrays;
public class InsertionSortDemo {    public static void insertionSort(int[] nums) {        int n = nums.length;        for (int i = 1; i < n; i++) {            int key = nums[i];            int j = i - 1;            while (j >= 0 && nums[j] > key) {                nums[j + 1] = nums[j];                j--;            }            nums[j + 1] = key;        }    }
    public static void main(String[] args) {        int[] arr = {12, 11, 13, 5, 6};        insertionSort(arr);        System.out.println(Arrays.toString(arr));    }}
Output
[5, 6, 11, 12, 13]

What this code does

  • key holds the incoming element being inserted into sorted prefix.
  • while loop shifts elements strictly greater than key to the right.
  • key drops into the vacated slot in O(1) assignment.

It takes each new element and shifts larger elements to the right until finding its correct insertion slot. Why is insertion sort widely used in production? On arrays that are already nearly sorted, insertion sort runs in nearly linear O(n) time. For small arrays (fewer than 16 elements), its simplicity and cache locality beat complex recursive algorithms. Consider tracing insertion sort on array [5, 1, 4, 2]: Key 1 at index 1: since 5 > 1, shift 5 right. Insert 1 at index 0: [1, 5, 4, 2]. Key 4 at index 2: since 5 > 4, shift 5 right. Insert 4 at index 1: [1, 4, 5, 2]. Key 2 at index 3: since 5 > 2 and 4 > 2, shift both right. Insert 2 at index 1: [1, 2, 4, 5]. The array is sorted in 3 insertion passes. Java's standard dual-pivot quicksort and TimSort algorithms switch to insertion sort for small subarrays. Insertion sort is also completely stable because equal elements are never shifted past each other.

  • Card-in-hand logic: insert incoming key into its proper position among sorted predecessors.
  • Adaptive performance: O(n) best-case time when array is already sorted or nearly sorted.
  • Hybrid building block: standard library sorts fall back to insertion sort for small sizes.

Next step

Check your understanding

10 quick questions