There are no items in your cart
Add More
Add More
Item Details | Price |
---|
Ever wondered how playing cards are sorted in your hands? You probably pick up one card at a time and place it in the right position among the cards you're already holding. That's exactly how Insertion Sort works! In this blog, we'll explore this intuitive sorting algorithm and break it down into simple, easy-to-understand steps.
Date: Sun Jan 5, 2025
For a visual explanation of the Insertion Sort algorithm, check out this detailed video tutorial:
Insertion Sort is like organizing a hand of cards as you receive them. Imagine you're dealing cards one by one. With each new card, you place it in the correct position among the cards you already have. This simple but effective method is exactly what makes Insertion Sort so intuitive!
Think of a librarian arranging books on a shelf. They:
Let's sort this list: [9, 5, 1, 4, 3]
Initial Array: [9, 5, 1, 4, 3]
Step 1: Compare 5 with 9
[5, 9, 1, 4, 3]
Step 2: Compare 1 with sorted portion
[1, 5, 9, 4, 3]
Step 3: Place 4 in correct position
[1, 4, 5, 9, 3]
Step 4: Finally, place 3
[1, 3, 4, 5, 9]
Final Sorted Array: [1, 3, 4, 5, 9]
def insertion_sort(arr):
# Start from the second element
for i in range(1, len(arr)):
# Store the current element
current_element = arr[i]
# Find where to insert current element
position = i - 1
while position >= 0 and arr[position] > current_element:
# Shift larger elements to the right
arr[position + 1] = arr[position]
position -= 1
# Insert the element in its correct position
arr[position + 1] = current_element
# Print step-by-step progress
print(f"Step {i}: {arr}")
return arr
# Example usage with our list
numbers = [9, 5, 1, 4, 3]
print(f"Original array: {numbers}")
sorted_numbers = insertion_sort(numbers)
print(f"Sorted array: {sorted_numbers}")
Try sorting this array by hand: [7, 2, 8, 1, 6]
- Best Case: O(n) - When the list is already sorted
- Average Case: O(n²) - For typical random data
- Worst Case: O(n²) - When the list is reverse sorted
In simple terms: For a list of 100 items, you might need up to 10,000 steps in the worst case!