๐ Day 55/150 – Insertion Sort in Python
Insertion Sort builds the sorted list one element at a time.It takes each element and inserts it into its correct position among the already sorted elements.
Works like sorting playing cards in your hand.
๐น Method 1 – Basic Insertion Sort
numbers = [12, 11, 13, 5, 6]
for i in range(1, len(numbers)):
key = numbers[i]
j = i - 1
while j >= 0 and numbers[j] > key:
numbers[j + 1] = numbers[j]
j -= 1
numbers[j + 1] = key
print("Sorted List:", numbers)
๐น Method 2 – Taking User Input
numbers = list(map(int, input("Enter numbers: ").split()))
for i in range(1, len(numbers)):
key = numbers[i]
j = i - 1
while j >= 0 and numbers[j] > key:
numbers[j + 1] = numbers[j]
j -= 1
numbers[j + 1] = key
print("Sorted List:", numbers)
๐น Method 3 – Sorting in Descending Order
numbers = [12, 11, 13, 5, 6]
for i in range(1, len(numbers)):
key = numbers[i]
j = i - 1
while j >= 0 and numbers[j] < key:
numbers[j + 1] = numbers[j]
j -= 1
numbers[j + 1] = key
print("Descending Order:", numbers)
๐น Method 4 – Using Function
def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr
print(insertion_sort([12, 11, 13, 5, 6]))
๐ก Key Takeaways
- Builds the sorted list one element at a time
- Efficient for small or nearly sorted lists
- Time Complexity: O(n²) in the worst case
- Stable sorting algorithm (keeps equal elements in order)
- Builds the sorted list one element at a time
- Efficient for small or nearly sorted lists
- Time Complexity: O(n²) in the worst case
- Stable sorting algorithm (keeps equal elements in order)
.png)

0 Comments:
Post a Comment