Bug hunt

Bubble Trouble

Bubble sort walks through the list comparing neighbours and swapping them if they are in the wrong order. After one pass, the biggest item has "bubbled" to the end. After i passes, the last i items are in place, so each pass can stop a little earlier.

a, b = b, a   # Python's one-line swap

Its cousin insertion sort takes each item and slides it left until it fits, like sorting a hand of cards. Both use nested loops, so both are O(n²). Fine for 50 items, painfully slow for a million.

The bug report

The guild's bubble_sort crashes with IndexError: list index out of range. And once that crash is fixed, the list comes out backwards (largest first)!

Assignment

Fix the two bugs so bubble_sort returns a new list sorted from smallest to largest, leaving the original list unchanged.