GAZAR

Principal Engineer | Mentor

Insertion Sort Algorithm

Insertion Sort Algorithm

Insertion sort works by iteratively selecting an element from the unsorted portion of the array and inserting it into its correct position in the sorted portion of the array. The algorithm maintains two subarrays: the sorted subarray and the unsorted subarray. Initially, the sorted subarray is empty, and the unsorted subarray contains all elements of the input array. In each iteration, insertion sort takes the first element from the unsorted subarray and inserts it into its correct position in the sorted subarray, shifting elements if necessary.

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

// Example usage:
const array = [5, 2, 4, 6, 1, 3];
console.log("Original Array:", array);
const sortedArray = insertionSort(array);
console.log("Sorted Array:", sortedArray);

The time complexity of insertion sort is O(n^2) in the worst case, where n is the number of elements in the array. However, insertion sort exhibits linear time complexity O(n) for nearly sorted arrays or small datasets.

Insertion sort is often used in applications where the dataset is small or nearly sorted, such as sorting a hand of playing cards or organizing a list of names in a phone book.


Comments