Loading subject…
| Pass | Comparison | Array before | Swap? | Array after |
|---|---|---|---|---|
| 1 | 5 > 1 | [5, 1, 4, 2] | Yes | [1, 5, 4, 2] |
| 1 | 5 > 4 | [1, 5, 4, 2] | Yes | [1, 4, 5, 2] |
| 1 | 5 > 2 | [1, 4, 5, 2] | Yes | [1, 4, 2, 5] |
| 2 | 1 > 4 | [1, 4, 2, 5] | No | [1, 4, 2, 5] |
| 2 | 4 > 2 | [1, 4, 2, 5] | Yes | [1, 2, 4, 5] |
| 3 | 1 > 2 | [1, 2, 4, 5] | No | [1, 2, 4, 5] |
| Pass (i) | Unsorted section | Values scanned | Smallest found | Swap | Array after |
|---|---|---|---|---|---|
| 0 | indices 0–3 | 5, 1, 4, 2 | 1 at index 1 | arr[0] and arr[1] | [1, 5, 4, 2] |
| 1 | indices 1–3 | 5, 4, 2 | 2 at index 3 | arr[1] and arr[3] | [1, 2, 4, 5] |
| 2 | indices 2–3 | 4, 5 | 4 at index 2 | arr[2] with itself | [1, 2, 4, 5] |
| Criterion | Bubble sort | Selection sort |
|---|---|---|
| Best case | O(n) with the swapped flag | O(n²), no early exit |
| Average case | O(n²) | O(n²) |
| Worst case | O(n²) | O(n²) |
| Space complexity | O(1), in place | O(1), in place |
| Comparisons on 4 items | Up to 6 | Exactly 6 |
| Swaps | Many, one per out-of-order pair | At most n − 1, one per pass |
| Stable | Yes | No |
| Best suited to | Small or nearly sorted data | Small data where writing is expensive |
def bubble_sort(arr): n = len(arr) for i in range(n - 1): swapped = False # has anything moved this pass? for j in range(n - 1 - i): # the last i items are already in place if arr[j] > arr[j + 1]: arr[j], arr[j + 1] = arr[j + 1], arr[j] swapped = True if not swapped: # already sorted, stop early break return arr
numbers = [5, 1, 4, 2]print(bubble_sort(numbers)) # Output: [1, 2, 4, 5]public static int[] bubbleSort(int[] arr) { int n = arr.length; for (int i = 0; i < n - 1; i++) { boolean swapped = false; // has anything moved this pass? for (int j = 0; j < n - 1 - i; j++) { // the last i items are already in place if (arr[j] > arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; swapped = true; } } if (!swapped) { // already sorted, stop early break; } } return arr;}
int[] numbers = {5, 1, 4, 2};System.out.println(Arrays.toString(bubbleSort(numbers))); // Output: [1, 2, 4, 5]def selection_sort(arr): n = len(arr) for i in range(n - 1): min_index = i # assume the first unsorted item is smallest for j in range(i + 1, n): if arr[j] < arr[min_index]: min_index = j # a smaller one was found arr[i], arr[min_index] = arr[min_index], arr[i] return arr
numbers = [5, 1, 4, 2]print(selection_sort(numbers)) # Output: [1, 2, 4, 5]public static int[] selectionSort(int[] arr) { int n = arr.length; for (int i = 0; i < n - 1; i++) { int minIndex = i; // assume the first unsorted item is smallest for (int j = i + 1; j < n; j++) { if (arr[j] < arr[minIndex]) { minIndex = j; // a smaller one was found } } int temp = arr[i]; arr[i] = arr[minIndex]; arr[minIndex] = temp; } return arr;}
int[] numbers = {5, 1, 4, 2};System.out.println(Arrays.toString(selectionSort(numbers))); // Output: [1, 2, 4, 5]