DSA Lab Manual(Insertion Sort )
DSA Lab Manual(Insertion Sort )
Theory:
Insertion Sort is a simple and efficient sorting algorithm that works similarly to the way you
might sort playing cards in your hands. It builds the sorted list one item at a time by repeatedly
picking the next item and inserting it into its correct position.
Key Characteristics:
• Time Complexity:
o Best Case: O(n) (when the array is already sorted)
o Worst Case: O(n²) (when the array is sorted in reverse order)
o Average Case: O(n²)
• Space Complexity: O(1) (In-place sorting algorithm)
• Stability: Insertion Sort is a stable sorting algorithm.
• Adaptive: Performs well when the array is already "nearly" sorted.
Algorithm:
Example Walkthrough:
Input:
Array: [5, 3, 8, 6, 2]
Iterations:
1. Key = 3; Compare with 5, shift 5; Insert 3. Result: [3, 5, 8, 6, 2]
2. Key = 8; Compare with 5; No shifts; Insert 8. Result: [3, 5, 8, 6, 2]
3. Key = 6; Compare with 8 and 5; Shift 8; Insert 6. Result: [3, 5, 6, 8, 2]
4. Key = 2; Compare with all elements; Shift all; Insert 2. Result: [2, 3, 5, 6, 8]
Lab Exercise:
Conclusion:
Insertion Sort is a fundamental sorting algorithm suitable for small or nearly sorted datasets. It
provides a foundation for understanding more complex sorting algorithms.