Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create insertion_sort.py #208

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions Python/insertion_sort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@

"""
Insertion sort is a simple sorting algorithm that builds the final sorted array (or list) one item at a time.
So in beginning we compare the first two elements and sort them by comparing them.
Then we pick the third element and find its proper position among the previous two sorted elements.
This way we gradually go on adding more elements to the already sorted list by putting them in their proper position.
"""
def insertion_sort(InputList):
for i in range(1, len(InputList)):
j = i-1
nxt_element = InputList[i]
# Compare the current element with next one
while (InputList[j] > nxt_element) and (j >= 0):
InputList[j+1] = InputList[j]
j=j-1
InputList[j+1] = nxt_element


numbers = [19,2,31,45,30,11,121,27]
insertion_sort(numbers)
print(numbers)