Insertion Sort - Part 1

  • + 0 comments

    My answer in Typescript, simple, not minimized

    function insertionSort1(n: number, arr: number[]): void {
        /**
         * simple as question requested.
         * 
         * + number [i] store index of arr
         * + number [x] store sorting element
         * 
         * index [i] move from end of [arr] to 0, check previous element [i - 1] is 
         * lower than [x] then replace [arr][i] by [x] then stop
         * orelse keep moving [index] replace current [arr][i] by [i - 1]
         */
        let i = arr.length - 1
        let x = arr[i]
    
        while (x != 0) {
            if ((arr[i - 1] ?? 0) < x) {
                arr[i] = x
                x = 0
            } else {
                arr[i] = arr[i - 1]
                i--
            }
            console.log(arr.join(' '))
        }
    }