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
-
Bubble Sort
- Let
rmark the right boundary of the unsorted part (initiallyr = n - 1). - For
j = 0..r-1, compare adjacent pairsa[j]anda[j+1]; swap if out of order. - After the pass, the largest value in
0..rhas bubbled to positionr. - Decrease
rby 1 and repeat until a pass makes no swaps (orr == 0).
- Let
-
Selection Sort
- Let
imark the boundary; the unsorted part isi..n-1(initiallyi = 0). - Find the index of the smallest element in
i..n-1. - Swap that element with the one at position
i. - Increase
iby 1 and repeat untili == n.
- Let
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 = 0swaps = 0for i in range(n):for j in range(n - i - 1):comparisons += 1if arr[j] > arr[j + 1]:arr[j], arr[j + 1] = arr[j + 1], arr[j]
swaps += 1print(f"Comparisons: {comparisons}, Swaps: {swaps}")return arrnumbers = [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 = 0swaps = 0for i in range(n):min_idx = ifor 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 arrnumbers = [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.