Skip to content

Instantly share code, notes, and snippets.

@KerryJones
Last active December 19, 2018 16:56
Show Gist options
  • Select an option

  • Save KerryJones/48ba24948671b361f68e to your computer and use it in GitHub Desktop.

Select an option

Save KerryJones/48ba24948671b361f68e to your computer and use it in GitHub Desktop.
Python Insertion Sort
##
# Insertion Sort
#
# Runtime complexity: O(n^2)
# Space complexity: O(1)
##
def insertion_sort(arr, detail = False):
for i in range(1, len(arr)):
j = i
while arr[j] < arr[j - 1] and j > 0:
arr[j], arr[j - 1] = arr[j - 1], arr[j]
j -= 1
if detail:
print(arr)
return arr
test_case = [5, 2, 1, 4, 3]
print(insertion_sort(test_case))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment