Insertion Sort

Data Structure and Algorithm 277 views Nov 05, 2025 1 min read

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
Share this Post
🚀 Want to Test Your Knowledge?

Take quizzes related to this topic and see where you stand!

Start Quiz Now
Back to Tutorials