Algo-Sim › Sorting & Divide and Conquer
Bubble Sort
Easy · Sorting & Divide and Conquer · step through it in Java, Python and C++ on your own input
Sweep left to right swapping out-of-order neighbours; each pass bubbles the largest remaining value to the end. Stop when a pass makes no swap.
Problem
Sort the integer array nums into ascending order using bubble sort: repeatedly sweep through the array, swapping neighbours that are out of order, until a sweep makes no swap.
Constraints
- O(n²) comparisons: fine for a few thousand values, too slow for 5 · 10⁴
- Sorts in place and is stable
Edge cases to test
- Already sorted: one pass with the early exit
- Reverse sorted: the worst case
- Duplicates (stable)
Follow-up questions
- When is bubble sort ever useful?
- Almost never in practice; it is O(n²) and does many swaps. The early exit makes it O(n) on sorted input, which insertion sort also achieves.
- Is it stable?
- Yes: it only swaps strictly out-of-order neighbours.
Solution
Java
public int[] bubbleSort(int[] nums) {
for (int end = nums.length - 1; end > 0; end--) {
boolean swapped = false;
for (int i = 0; i < end; i++) {
if (nums[i] > nums[i + 1]) {
int t = nums[i]; nums[i] = nums[i + 1]; nums[i + 1] = t;
swapped = true;
}
}
if (!swapped) break;
}
return nums;
}Python
def bubble_sort(nums):
for end in range(len(nums) - 1, 0, -1):
swapped = False
for i in range(end):
if nums[i] > nums[i + 1]:
nums[i], nums[i + 1] = nums[i + 1], nums[i]
swapped = True
if not swapped:
break
return numsC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<int> bubbleSort(vector<int> &nums) {
for (int end = int(nums.size()) - 1; end > 0; end--) {
bool swapped = false;
for (int i = 0; i < end; i++) {
if (nums[i] > nums[i + 1]) {
int t = nums[i];
nums[i] = nums[i + 1];
nums[i + 1] = t;
swapped = true;
}
}
if (!swapped)
break;
}
return nums;
}
};
More Sorting & Divide and Conquer problems
- Insertion Sort (Easy)
- Selection Sort (Easy)
- Merge Sort (Medium)
- Quick Sort (Lomuto) (Medium)
- Quick Sort (Hoare) (Medium)
- Counting Sort (Easy)
- Radix Sort (LSD) (Medium)
- Bucket Sort (Medium)
- Kth Largest Element (Quickselect) (Medium)
- Count Inversions (Hard)
- Largest Number (Medium)