Bubble sort sorts a list by stepping through it repeatedly, comparing each pair of adjacent elements and swapping them when they are in the wrong order. Each pass carries the largest remaining value toward the end of the unsorted part, and the passes repeat until the list is sorted.
Write a function that takes a list of integers nums and sorts it in ascending order using bubble sort.
Function Signature
def bubble_sort(nums: list[int]) -> list[int]:
Rules
-
Sort
nums
in place and return it.
-
Keep duplicates: the output has the same length and the same values as the input.
-
Implement the comparisons and swaps yourself instead of calling
sorted()
or
list.sort()
.
Constraints
-
1 <= len(nums) <= 10^4
-
-10^4 <= nums[i] <= 10^4
Examples
Input: nums = [64, 34, 25, 12, 22, 11, 90]
Output: [11, 12, 22, 25, 34, 64, 90]
The output is the seven values in ascending order. The first pass already leaves 64 and 90 in the last two positions, because 64 is swapped right until it meets the larger 90.
Input: nums = [3, -1, 3, 0, -5]
Output: [-5, -1, 0, 3, 3]
Negative values sort below zero, and both copies of 3 stay in the output.
Input: nums = [1, 2, 3]
Output: [1, 2, 3]
The list is already sorted. The first pass makes no swaps, so an implementation that stops early can finish after one pass.