Mastery Points
0

Insertion Sort in dsa

Context & Logic

Insertion Sort builds the final sorted array one item at a time.

Example

function insertionSort(arr) {
    for (let i = 1; i < arr.length; i++) {
        let key = arr[i], j = i - 1;
        while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j--; }
        arr[j + 1] = key;
    }
    return arr;
}

Step-by-Step Logic

1

Pick an element and insert it into its correct position relative to the sorted part.

Complexity Metrics

Time Efficiency

O(n²) average, O(n) best-case

Memory Footprint

O(1)