Bubble Sort
Solve this ProblemTest Case 1:
Test Case 2:
Test Case 3:
Constraints
- ◆
0 ≤ arr.length ≤ 200 - ◆
-1000 ≤ arr[i] ≤ 1000 - ◆
Sort in non-decreasing order
Try the Dry Run
Don't just read the solution — watch it execute, one step at a time.
Approach & Solutions
Brute Force — Fixed Number of Passes
GoodRepeatedly sweep across the array, swapping any adjacent pair that's out of order — each full sweep "bubbles" the largest remaining value to its final position at the end. Doing this for n-1 sweeps guarantees the whole array is sorted. Correct, but it always runs every single sweep, even on a sweep where nothing needed swapping — there's no way to notice the array became sorted early and stop.
O(n²)O(1)1class Solution {
2 public int[] bubbleSort(int[] arr) {
3 int n = arr.length;
4 for (int i = 0; i < n - 1; i++) {
5 for (int j = 0; j < n - 1 - i; j++) {
6 if (arr[j] > arr[j + 1]) {
7 int temp = arr[j];
8 arr[j] = arr[j + 1];
9 arr[j + 1] = temp;
10 }
11 }
12 }
13 return arr;
14 }
15}Optimal — Early Exit via Swapped Flag
OptimalSame sweeping idea, but track whether a sweep actually swapped anything. If a whole sweep goes by with zero swaps, the array is already sorted — stop immediately instead of running the remaining sweeps for nothing. Worst case is still O(n²), but on data that's already sorted (or close to it) this finishes in a single O(n) pass.
O(n²)O(1)1class Solution {
2 public int[] bubbleSort(int[] arr) {
3 int n = arr.length;
4 for (int i = 0; i < n - 1; i++) {
5 boolean swapped = false;
6 for (int j = 0; j < n - 1 - i; j++) {
7 if (arr[j] > arr[j + 1]) {
8 int temp = arr[j];
9 arr[j] = arr[j + 1];
10 arr[j + 1] = temp;
11 swapped = true;
12 }
13 }
14 if (!swapped) break;
15 }
16 return arr;
17 }
18}