chore(Python): added Recursive Insertion Sort (#457)

pull/465/head
Mohammad Shakib 2021-09-13 18:58:42 +06:00 committed by GitHub
parent c82cbee76d
commit 8b23149ae8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 31 additions and 0 deletions

View File

@ -20,6 +20,7 @@
1. [Factorial](recursion/factorial.py) 1. [Factorial](recursion/factorial.py)
2. [n-th Fibonacci number](recursion/n-th_fibonacci_number.py) 2. [n-th Fibonacci number](recursion/n-th_fibonacci_number.py)
3. [Recursive Insertion Sort](recursion/recursive_insertion_sort.py)
## Scheduling ## Scheduling

View File

@ -0,0 +1,30 @@
"""
Base Case: If array size is 1 or smaller, return.
Recursively sort first n-1 elements.
Insert last element at its correct position in sorted array.
"""
def insertionSort_rec(array, n):
# base case
if n <= 1:
return
# Sort first n-1 elements
insertionSort_rec(array, n-1)
'''Insert last element at its correct position
in sorted array.'''
end = array[n-1]
j = n-2
# Move elements of arr[0..i-1], that are
# greater than key, to one position ahead
# of their current position
while (j >= 0 and array[j] > end):
array[j+1] = array[j]
j -= 1
array[j+1] = end
arr = [6, 5, 2, 7, 12, 9, 1, 4]
insertionSort_rec(arr, len(arr))
print("Sorted array is:")
print(arr)