easy +8 pts

Bubble Sort

Implement classic bubble sort and return the sorted list.

Write a function `bubble_sort(arr)` that takes a list of numbers and returns a new list sorted in ascending order using the bubble sort algorithm. The original list should not be modified. Bubble sort works by repeatedly stepping through the list, comparing adjacent elements and swapping them if they are in the wrong order. The process is repeated until no swaps are needed. Your implementation must actually perform the swaps; do not simply call `arr.sort()` or `sorted()`.

Constraints

Input list may contain integers or floats. The length of the list is between 0 and 1000. The function should run in O(n^2) time in the worst case and O(1) extra space (ignoring the output list).

Example

>>> bubble_sort([3, 1, 2])
[1, 2, 3]
>>> bubble_sort([5, 5, 5])
[5, 5, 5]
>>> bubble_sort([])
[]
>>> bubble_sort([-1, 0, 3, -2])
[-2, -1, 0, 3]
8 points ~12 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Perform multiple passes through the list, swapping adjacent elements that are out of order.
After each pass, the largest remaining element bubbles to the end, so you can reduce the range.
If a complete pass makes no swaps, the list is already sorted; you can stop early.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.