forked from souravjain540/Basic-Python-Programs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertionSort,py
More file actions
27 lines (21 loc) · 715 Bytes
/
InsertionSort,py
File metadata and controls
27 lines (21 loc) · 715 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# Insertion Sort in python
# Time Complexity
# Best O(n)
# Worst O(n^2)
# Average O(n^2)
# Space Complexity O(1)
def insertionSort(array):
for step in range(1, len(array)):
key = array[step]
j = step - 1
# Compare key with each element on the left of it until an element smaller than it is found
# For descending order, change key<array[j] to key>array[j].
while j >= 0 and key < array[j]:
array[j + 1] = array[j]
j = j - 1
# Place key at after the element just smaller than it.
array[j + 1] = key
data = [19, 14, 1, 44, 23]
insertionSort(data)
print('Sorted Array in Ascending Order:')
print(data)