Bubble & Selection Sorts

What Are Sorting Algorithms?

Sorting algorithms are used to arrange elements in a specific order (ascending or descending).

Two common sorting methods are Bubble Sort and Selection Sort.

Comparison of Bubble Sort and Selection Sort

Algorithm Time Complexity Space Complexity Visualisation
Bubble Sort O(n²) - very slow for large datasets O(1) - no extra space is required Visualisation;
alt Visualisation
Selection Sort O(n²) - not efficient for large datasets O(1) - no extra space is required Visualisation;
alt Visualisation (choose SEL)

Example: Implementing Sorting Algorithms

Algorithm Steps

  1. Bubble Sort
    1. Let r mark the right boundary of the unsorted part (initially r = n - 1).
    2. For j = 0..r-1, compare adjacent pairs a[j] and a[j+1]; swap if out of order.
    3. After the pass, the largest value in 0..r has bubbled to position r.
    4. Decrease r by 1 and repeat until a pass makes no swaps (or r == 0).
  2. Selection Sort
    1. Let i mark the boundary; the unsorted part is i..n-1 (initially i = 0).
    2. Find the index of the smallest element in i..n-1.
    3. Swap that element with the one at position i.
    4. Increase i by 1 and repeat until i == n.

Bubble Sort Implementation

The classic implementation of a Bubble Sort is to use nested counted loops; i.e. nested FOR...TO...NEXT loops.

Python: Classic Bubble Sort

def bubble_sort(arr):
  n = len(arr)
  comparisons = 0
  swaps = 0
  for i in range(n):
    for j in range(n - i - 1):
      comparisons += 1
      if arr[j] > arr[j + 1]:
        arr[j], arr[j + 1] = arr[j + 1], arr[j]
        swaps += 1
    
  print(f"Comparisons: {comparisons}, Swaps: {swaps}")
  return arr

numbers = [64,34,25,12,22,11,90]
print("Sorted Array:", bubble_sort(numbers))

Java: Classic Bubble Sort

public class BubbleSort {
  public static int[] bubbleSort(int[] arr) {
    int n = arr.length;
    int comparisons = 0, swaps = 0;
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < n - i - 1; j++) {
        comparisons++;
        if (arr[j] > arr[j + 1]) {
          int temp = arr[j];
          arr[j] = arr[j + 1];
          arr[j + 1] = temp;
          swaps++;
        }
      }
    }
    System.out.println("Comparisons: " + comparisons + ", Swaps: " + swaps);
    return arr;
  }

  public static void main(String[] args) {
    int[] numbers = {64,34,25,12,22,11,90};
    bubbleSort(numbers);
    System.out.println("Sorted Array: " + java.util.Arrays.toString(numbers));
  }
}

Refined Bubble Sort Implementation

It is possible to fine-tune Bubble Sort: stop early if a full pass makes no swaps, and shrink the inner loop’s upper bound to the index of the last swap. These tweaks improve performance on nearly sorted data.

Python: Refined Bubble Sort

def bubble_sort_refined(arr):
    """
    Tweaks:
      1) Early exit if an entire pass makes no swaps.
      2) Reduce the inner loop's upper bound to the last swap index.
    """
    n = len(arr)
    comparisons = 0
    swaps = 0

    while n > 1:
        last_swap = 0
        for j in range(n - 1):
            comparisons += 1
            if arr[j] > arr[j + 1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
                swaps += 1
                last_swap = j + 1  # everything after this is already in place for this pass
        if last_swap == 0:
            print("Early exit: no swaps on last pass")
            break
        n = last_swap  # next pass only needs to bubble up to the last swap point

    print(f"Comparisons: {comparisons}, Swaps: {swaps}")
    return arr

numbers = [64, 34, 25, 12, 22, 11, 90]
print("Sorted Array:", bubble_sort_refined(numbers))

Java: Refined Bubble Sort

import java.util.Arrays;

public class BubbleSortRefined {
    public static int[] bubbleSortRefined(int[] arr) {
        int n = arr.length;
        int comparisons = 0, swaps = 0;

        while (n > 1) {
            int lastSwap = 0;
            for (int j = 0; j < n - 1; j++) {
                comparisons++;
                if (arr[j] > arr[j + 1]) {
                    int tmp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = tmp;
                    swaps++;
                    lastSwap = j + 1; // elements after this are already in place for this pass
                }
            }
            if (lastSwap == 0) {
                System.out.println("Early exit: no swaps on last pass");
                break;
            }
            n = lastSwap; // shrink upper bound to the last swap index
        }

        System.out.println("Comparisons: " + comparisons + ", Swaps: " + swaps);
        return arr;
    }

    public static void main(String[] args) {
        int[] numbers = {64, 34, 25, 12, 22, 11, 90};
        bubbleSortRefined(numbers);
        System.out.println("Sorted Array: " + Arrays.toString(numbers));
    }
}

Selection Sort Implementation

Python: Selection Sort

def selection_sort(arr):
  n = len(arr)
  comparisons = 0
  swaps = 0
  for i in range(n):
    min_idx = i
    for j in range(i + 1, n):
      comparisons += 1
      if arr[j] < arr[min_idx]:
        min_idx = j
    
    arr[i], arr[min_idx] = arr[min_idx], arr[i]
    swaps += 1
  
  print(f"Comparisons: {comparisons}, Swaps: {swaps}")
  return arr

numbers = [64,34,25,12,22,11,90]
print("Sorted Array:", selection_sort(numbers))

Java: Selection Sort

public class SelectionSort {
  public static int[] selectionSort(int[] arr) {
    int n = arr.length;
    int comparisons = 0, swaps = 0;
    for (int i = 0; i < n; i++) {
      int minIdx = i;
      for (int j = i + 1; j < n; j++) {
        comparisons++;
        if (arr[j] < arr[minIdx]) {
          minIdx = j;
        }
      }
      int temp = arr[minIdx];
      arr[minIdx] = arr[i];
      arr[i] = temp;
      swaps++;
    }
    System.out.println("Comparisons: " + comparisons + ", Swaps: " + swaps);
    return arr;
  }

  public static void main(String[] args) {
    int[] numbers = {64,34,25,12,22,11,90};
    selectionSort(numbers);
    System.out.println("Sorted Array: " + java.util.Arrays.toString(numbers));
  }
}

Choosing the Right Sorting Algorithm

  • Use Bubble Sort when:
    • Dataset is small.
    • Data is almost sorted, minimising swaps.
  • Use Selection Sort when:
    • Swapping is costly (e.g. limited write cycles).
    • Dataset is small and simplicity is preferred.

 Key Takeaways

  • Bubble Sort and Selection Sort both run in O(n²) time.
  • Bubble Sort excels on nearly sorted data; Selection Sort minimises swaps.
  • Neither is suitable for large datasets—consider merge sort or quicksort instead.
  • Built-in sorting functions in both Python and Java use more efficient algorithms under the hood.