Bubble Sort
Pattern: Basic sorts
Sort by swapping neighbours that are in the wrong order. Each pass carries the largest remaining value to the end, and a pass with no swaps means you can stop.
The problem
You are given an array of between 1 and 1500 whole numbers. Sort it in increasing order using bubble sort, and return it.
For example, [4, 3, 1, 2] becomes [1, 2, 3, 4].
On the original site the problem is written a little differently, so use the link above for its exact wording. The
function name bubbleSort and the limits are this guide's own.
Think first
- Walk along
[4, 3, 1, 2]once, swapping any neighbours in the wrong order. Where does the 4 end up? - After one such pass, which position is guaranteed to be final?
- How can you tell, during a pass, that the whole array is already sorted?
Hints
Brute force, and why it fails
Without the early stop, bubble sort always makes n - 1 passes, even on an array that is already sorted. With a swapped
flag it finishes after one pass on sorted input. Either way, the worst case (a reversed array) is O(n²).
The key insight
Every pass pushes the largest remaining value to its final place, so the unsorted part shrinks by one each time. A pass with no swaps proves that everything is already in order.
Dry run
| end | 3 |
|---|---|
| swapped | true |
nums = [4, 3, 1, 2]. Pass 1 compares neighbours from the left. 4 and 3 are in the wrong order, so swap them.
The plan
for end from n - 1 down to 1:
swapped = false
for j from 0 to end - 1:
if nums[j] > nums[j + 1]: # wrong order
swap nums[j] and nums[j + 1]
swapped = true
if not swapped:
stop # already sorted
return nums
Complexity
- Time
O(n²)- Space
O(1)
At most about n²/2 comparisons and swaps (on a reversed array). On sorted input the early stop makes it O(n).
Edge cases
- One element: no passes run.
- Already sorted: one pass and no swaps.
- Reversed: every comparison swaps, which is the worst case.
- Equal neighbours are not swapped (
>and not>=), so bubble sort is stable.
I've built my logic, show the code
Java
class Solution {
public int[] bubbleSort(int[] nums) {
int n = nums.length;
for (int end = n - 1; end > 0; end--) {
boolean swapped = false;
for (int j = 0; j < end; j++) {
if (nums[j] > nums[j + 1]) { // neighbours in the wrong order
int temp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = temp;
swapped = true;
}
}
if (!swapped) {
break; // a pass with no swaps: already sorted
}
}
return nums;
}
}C++
class Solution {
public:
vector<int> bubbleSort(vector<int>& nums) {
int n = static_cast<int>(nums.size());
for (int end = n - 1; end > 0; end--) {
bool swapped = false;
for (int j = 0; j < end; j++) {
if (nums[j] > nums[j + 1]) { // neighbours in the wrong order
swap(nums[j], nums[j + 1]);
swapped = true;
}
}
if (!swapped) {
break; // a pass with no swaps: already sorted
}
}
return nums;
}
};Python
class Solution:
def bubbleSort(self, nums):
n = len(nums)
for end in range(n - 1, 0, -1):
swapped = False
for j in range(end):
if nums[j] > nums[j + 1]: # neighbours in the wrong order
nums[j], nums[j + 1] = nums[j + 1], nums[j]
swapped = True
if not swapped:
break # a pass with no swaps: already sorted
return numsCommon mistakes
- Letting
jreachendand readingnums[end + 1], past the array. - Swapping on
>=, which makes equal values trade places, so the sort is no longer stable. - Forgetting to reset
swappedat the start of each pass.