Implement bubble sort with early exit
Standard · Write code · about 10 min
Sort nums in ascending order with bubble sort and return it.
Stop as soon as a pass makes no swaps: then the array is already sorted.
Example 1
Input:
[[5,1,4,2,8]]
Output:
[1,2,4,5,8]
Example 2
Input:
[[1,2,3,4,5]]
Output:
[1,2,3,4,5]
Sorted input: one pass with no swaps, then stop.
Constraints
- 0 ≤ nums.length ≤ 1,000
- -1,000 ≤ nums[i] ≤ 1,000
Learn the idea first: Bubble sort, a visual lesson.
More Bubble sort problems
- State after one pass Warm-up
- Count swaps Warm-up
- Array after k passes Standard
- How many swaps? Standard
- Spot the bug: the last pair Standard
- Count passes until sorted Challenge