diff --git a/code_to_optimize/bubble_sort_3.py b/code_to_optimize/bubble_sort_3.py index db7db5f92..67c2d38c3 100644 --- a/code_to_optimize/bubble_sort_3.py +++ b/code_to_optimize/bubble_sort_3.py @@ -1,8 +1,10 @@ def sorter(arr): - for i in range(len(arr)): - for j in range(len(arr) - 1): - if arr[j] > arr[j + 1]: - temp = arr[j] - arr[j] = arr[j + 1] - arr[j + 1] = temp + # Insertion sort: much faster than bubble sort for nearly-sorted or small lists + for i in range(1, len(arr)): + key = arr[i] + j = i - 1 + while j >= 0 and arr[j] > key: + arr[j + 1] = arr[j] + j -= 1 + arr[j + 1] = key return arr