Skip to content

Commit 5492cd1

Browse files
committed
Insertion Sort
1 parent 05655cf commit 5492cd1

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,4 +24,5 @@ Data Structures and Algorithms Patterns implemented in Python.
2424
- [x] [Binary Search](Searching-Algo/binarysearch.py)
2525
- [x] [Sorting Alogorithms](Sorting-Algo)
2626
- [x] [Bubble Sort](Sorting-Algo/bubblesort.py)
27+
- [x] [Insertion Sort](Sorting-Algo/insertionsort.py)
2728

Sorting-Algo/insertionsort.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
'''
2+
Insertion Sort
3+
Insertion sort is a sorting algorithm that places an unsorted element at its suitable place in each iteration.
4+
5+
Time Complexity - O(n)
6+
'''
7+
def insertionSort(list):
8+
9+
for step in range(1, len(list)):
10+
target = list[step]
11+
j = step - 1
12+
13+
# Compare target with each element on the left of it until an element smaller than it is found
14+
# For descending order, change target<list[j] to target>list[j].
15+
while j >= 0 and target < list[j]:
16+
list[j + 1] = list[j]
17+
j = j - 1
18+
19+
# Place target at after the element just smaller than it.
20+
list[j + 1] = target
21+
22+
23+
list = [9, 5, 1, 4, 3]
24+
insertionSort(list)
25+
print(list) #[1, 3, 4, 5, 9]

0 commit comments

Comments
 (0)