Created
October 22, 2017 10:27
-
-
Save rajatdiptabiswas/e4cb7d252cfd8920a6267714e6b18269 to your computer and use it in GitHub Desktop.
Sorting Algorithm: Insertion Sort
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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