-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsertion_sort.py
More file actions
23 lines (20 loc) · 847 Bytes
/
insertion_sort.py
File metadata and controls
23 lines (20 loc) · 847 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
def insertion_sort(data_list):
"""
Sorts a list using the Insertion Sort algorithm by shifting and inserting elements.
"""
# Start from the second element (index 1) as the first is considered sorted
for i in range(1, len(data_list)):
key = data_list[i] # Current element to be positioned
j = i - 1
# Shift elements of the sorted portion that are larger than the key
while j >= 0 and key < data_list[j]:
data_list[j + 1] = data_list[j]
j -= 1
# Place the key in its correct sorted position
data_list[j + 1] = key
# Testing the implementation
if __name__ == "__main__":
test_list = [44, 55, 12, 42, 94, 18, 6, 67]
print(f"Original list (Insertion): {test_list}")
insertion_sort(test_list)
print(f"Sorted list (Insertion): {test_list}")