What is insertion sort?

Answer

Insertion sort builds the sorted array one element at a time by inserting each new element into its correct position among the already-sorted elements — like sorting playing cards in your hand. Algorithm: for i from 1 to n-1, take arr[i] as the key, compare with elements to its left, shift larger elements right, insert key in its correct position. Time: O(n²) worst (reverse sorted), O(n) best (already sorted — only n-1 comparisons, 0 swaps). Space: O(1) in-place. Stable: yes. Advantages: efficient for small arrays (typically used for n ≤ 10-20); efficient for nearly-sorted data; simple implementation; online algorithm (can sort as elements arrive); no extra memory. Used as the base case in hybrid sorts: Timsort (Python, Java) uses insertion sort for small subarrays (< ~64 elements) then merge sort; Introsort (C++ std::sort) uses insertion sort for small subarrays. In competitive programming: insertion sort is preferred over other O(n²) sorts for small or nearly-sorted inputs. The O(n) best case makes it excel at sorting nearly-sorted data, which is common in practice.