Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

A recursive insertion sort #1683

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

Merged
merged 2 commits into from
Jan 13, 2020
Merged
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
72 changes: 72 additions & 0 deletions sorts/recursive_insertion_sort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
"""
A recursive implementation of the insertion sort algorithm
"""

from typing import List

def rec_insertion_sort(collection: List, n: int):
"""
Given a collection of numbers and its length, sorts the collections
in ascending order

:param collection: A mutable collection of comparable elements
:param n: The length of collections

>>> col = [1, 2, 1]
>>> rec_insertion_sort(col, len(col))
>>> print(col)
[1, 1, 2]

>>> col = [2, 1, 0, -1, -2]
>>> rec_insertion_sort(col, len(col))
>>> print(col)
[-2, -1, 0, 1, 2]

>>> col = [1]
>>> rec_insertion_sort(col, len(col))
>>> print(col)
[1]
"""
#Checks if the entire collection has been sorted
if len(collection) <= 1 or n <= 1:
return


insert_next(collection, n-1)
rec_insertion_sort(collection, n-1)

def insert_next(collection: List, index: int):
"""
Inserts the '(index-1)th' element into place

>>> col = [3, 2, 4, 2]
>>> insert_next(col, 1)
>>> print(col)
[2, 3, 4, 2]

>>> col = [3, 2, 3]
>>> insert_next(col, 2)
>>> print(col)
[3, 2, 3]

>>> col = []
>>> insert_next(col, 1)
>>> print(col)
[]
"""
#Checks order between adjacent elements
if index >= len(collection) or collection[index - 1] <= collection[index]:
return

#Swaps adjacent elements since they are not in ascending order
collection[index - 1], collection[index] = (
collection[index], collection[index - 1]
)

insert_next(collection, index + 1)

if __name__ == "__main__":
numbers = input("Enter integers seperated by spaces: ")
numbers = [int(num) for num in numbers.split()]
rec_insertion_sort(numbers, len(numbers))
print(numbers)