(nums)
| 1 | def insertion_sort(nums): |
| 2 | # Start on the second element as we assume the first element is sorted |
| 3 | for i in range(1, len(nums)): |
| 4 | item_to_insert = nums[i] |
| 5 | # And keep a reference of the index of the previous element |
| 6 | j = i - 1 |
| 7 | # Move all items of the sorted segment forward if they are larger than |
| 8 | # the item to insert |
| 9 | while j >= 0 and nums[j] > item_to_insert: |
| 10 | nums[j + 1] = nums[j] |
| 11 | j -= 1 |
| 12 | # Insert the item |
| 13 | nums[j + 1] = item_to_insert |
| 14 | |
| 15 | |
| 16 | # Verify it works |