Insertion Sort: Algorithm & Implementation
1️⃣ What is Insertion Sort?
🔹 Insertion Sort is a simple sorting algorithm that builds the sorted array one item at a time.
🔹 It compares each element with the previous ones and inserts it at the correct position.
🔹 Best suited for small or nearly sorted datasets.
✅ Time Complexity
Case | Complexity |
---|---|
Best Case (Already Sorted) | O(n) |
Average Case | O(n²) |
Worst Case (Reversed Order) | O(n²) |
✅ Space Complexity
- O(1) (In-place sorting)
✅ Is it Stable?
✔ Yes (Preserves order of equal elements)
2️⃣ How Insertion Sort Works
🔹 The algorithm divides the array into sorted and unsorted parts.
🔹 It picks an element from the unsorted part and inserts it into the correct position in the sorted part.
Step-by-Step Example
📝 Input: [8, 4, 1, 6, 3]
Step | Key Element | Sorted Part | Unsorted Part | Action |
---|---|---|---|---|
1 | 4 | 8 | 4, 1, 6, 3 | Move 8 right, Insert 4 |
2 | 1 | 4, 8 | 1, 6, 3 | Move 8, 4 right, Insert 1 |
3 | 6 | 1, 4, 8 | 6, 3 | Move 8 right, Insert 6 |
4 | 3 | 1, 4, 6, 8 | 3 | Move 6, 4 right, Insert 3 |
🔹 Final Sorted Array: [1, 3, 4, 6, 8]
3️⃣ Insertion Sort Algorithm
🔹 Pseudocode
4️⃣ Insertion Sort Implementation in C
🔹 Output
5️⃣ Advantages & Disadvantages
✅ Advantages
✔ Simple & easy to implement
✔ Works well for small datasets
✔ Efficient for nearly sorted data (O(n) best case)
✔ In-place sorting (O(1) space)
❌ Disadvantages
❌ Inefficient for large datasets (O(n²) worst case)
❌ Slower than Quick Sort & Merge Sort for large inputs
6️⃣ When to Use Insertion Sort?
🔹 Best for small datasets (e.g., <100 elements).
🔹 Great for nearly sorted data (performs in O(n) time).
🔹 Used in real-world scenarios like card sorting or keyboard typing auto-sorting.
💡 For larger datasets, use Merge Sort or Quick Sort! 🚀
No comments:
Post a Comment