Skip to content

Commit 4462f6d

Browse files
committed
add insertion sort
1 parent d2ff15e commit 4462f6d

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

insertion_sort.py

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# Insertion Sort Implementation
2+
3+
# Main function that takes
4+
# arr --> Array to be sorted
5+
def insertionSort(arr):
6+
7+
for i in range(1, len(arr)):
8+
9+
# get current element
10+
key = arr[i]
11+
12+
# Move elements that are greater than key
13+
# to one position ahead of their current position
14+
j = i - 1
15+
while j >=0 and key < arr[j] :
16+
arr[j+1] = arr[j]
17+
j -= 1
18+
arr[j+1] = key
19+
20+
# Test
21+
arr = [12, 11, 13, 5, 6, 9, 8]
22+
print ("Original array is: {}".format(arr))
23+
insertionSort(arr)
24+
print ("Sorted array is: {}".format(arr))

0 commit comments

Comments
 (0)