-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathinsertion_sort.py
More file actions
52 lines (38 loc) · 1.4 KB
/
insertion_sort.py
File metadata and controls
52 lines (38 loc) · 1.4 KB
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
"""
Insertion Sort Algorithm
Insertion Sort builds the final sorted array one item at a time.
It is much less efficient on large lists than more advanced algorithms,
but provides several advantages: simple implementation, efficient for small data sets,
and adaptive (efficient for data sets that are already substantially sorted).
Time Complexity:
- Best Case: O(n) - when array is already sorted
- Average Case: O(n²)
- Worst Case: O(n²)
Space Complexity: O(1) - in-place sorting
Stable: Yes (maintains relative order of equal elements)
"""
def insertion_sort(arr):
"""
Sorts an array using the Insertion Sort algorithm.
Args:
arr: List of comparable elements to be sorted (modified in-place)
Returns:
None (sorts in-place)
"""
# Traverse from 1 to len(arr)
for i in range(1, len(arr)):
key = arr[i] # Current element to be inserted
# Move elements of arr[0..i-1] that are greater than key
# one position ahead of their current position
j = i - 1
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
# Insert key at its correct position
arr[j + 1] = key
# Example usage
if __name__ == "__main__":
numbers = [64, 34, 25, 12, 22, 11, 90]
print(f"Original array: {numbers}")
insertion_sort(numbers)
print(f"Sorted array: {numbers}")