Insertion Sort

1. Introduction

1.1. How does Insertion Sort work?

1.2. Illustration of Insertion Sort

2. Code

        const insertionSort = (arr) => {
            let sortedArr = [...arr]; // A copy of the array

            for(let i = 1; i < sortedArr.length; i++) {
                let key = arr[i];
                let j = i - 1;

                /* Move elements of arr[0..i-1], that are greater than key, 
                to one position ahead of their current position */
                while (j >= 0 && sortedArr[j] > key) {
                    sortedArr[j + 1] = sortedArr[j];
                    j -= 1;
                }
                sortedArr[j + 1] = key;
            }
            return sortedArr;
        };

        const arr = [23, 1, 10, 5, 2];
        document.getElementById('originalArray').textContent = "Original Array: " + arr;

        const sortedArr = insertionSort(arr);
        document.getElementById('sortedArray').textContent = "Sorted Array: " + sortedArr;

Output:

Explanation

The initial array: [23, 1, 10, 5, 2].
The first element (23) is considered sorted by itself. 23 > 1? → [1, 23, 10, 5, 2] 23 > 10? → [1, 10, 23, 5, 2] 23 > 5? → [1, 10, 5, 23, 2], 10 > 5? → [1, 5, 10, 23, 2], 5 > 1? → [1, 5, 10, 23, 2] 23 > 2? → [1, 5, 10, 2, 23], 10 > 2? → [1, 5, 2, 10, 23], 5 > 2? → [1, 2, 5, 10, 23], 2 > 1? → [1, 2, 5, 10, 23]

4. Conclusion

References