Skip to content

Instantly share code, notes, and snippets.

@rajatdiptabiswas
Created October 22, 2017 10:27
Show Gist options
  • Save rajatdiptabiswas/e4cb7d252cfd8920a6267714e6b18269 to your computer and use it in GitHub Desktop.
Save rajatdiptabiswas/e4cb7d252cfd8920a6267714e6b18269 to your computer and use it in GitHub Desktop.
Sorting Algorithm: Insertion Sort
#!/usr/bin/env python3
#Insertion Sort
def insertion_sort(array):
# Traverse through 1 to len(arr)
for x in range(1, len(array)):
y = x-1
key = array[x]
# Move elements of arr[0..x-1], that are
# greater than key, to one position ahead
# of their current position
while (y >= 0 and array[y] > key):
array[y+1] = array[y]
y -= 1
array[y+1] = key
# Main
print("Enter the elements of the array to be sorted")
arr = [int(n) for n in input().split()]
insertion_sort(arr)
print("The sorted array is")
print(arr)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment