Skip to content

Commit a318f08

Browse files
authored
Create InsertionSort.py
Insertion Sort Implementation In Python In order to rank an array of size N ascendingly: Over the array, iterate from arr[1] to arr[N]. Comparing the current (key) element to the previous one. Compare the key element to the previous elements to see if it is smaller. In order to make room for the substituted element, move the larger elements up one position.
1 parent 9629aef commit a318f08

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

InsertionSort.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
def insertion_sort(arr):
2+
3+
for i in range(1, len(arr)):
4+
key = arr[i]
5+
j = i - 1
6+
7+
while j >= 0 and key < arr[j]:
8+
arr[j + 1] = arr[j]
9+
j = j - 1
10+
11+
12+
arr[j + 1] = key
13+
14+
arr = [9, 8, 6, 7, 1]
15+
print("Unsorted Array:", arr)
16+
insertion_sort(arr)
17+
print('Sorted Array: ', arr)

0 commit comments

Comments
 (0)