Insertion Sort
π Data Structure and Algorithm
π 96 views
π
Nov 05, 2025
β± Estimated reading time: 1 min
Insertion Sort Algorithm
Insertion Sort builds the sorted list one element at a time by inserting elements into their correct positions.
Algorithm Steps
- Start from the second element.
- Compare it with previous elements.
- Shift larger elements one position ahead.
- Insert the key in the correct position.
Example (C++)
void insertionSort(int arr[], int n) {
for (int i = 1; i < n; i++) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}
Time Complexity
- Best: O(n)
- Worst: O(nΒ²)
Advantages
- Efficient for small or nearly sorted data.
Disadvantages
- Inefficient for large datasets.
Conclusion
Insertion sort performs well on small or nearly sorted data, making it suitable for small applications.
π Some advanced sections are available for Registered Members
Register Now
Register Now
Share this Post
β Back to Tutorials