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

  1. Start from the second element.
  2. Compare it with previous elements.
  3. Shift larger elements one position ahead.
  4. 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

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes