Correctness and the Loop Invariant

  • + 0 comments

    wtf happen to my editor? my Typescript just only main() and have no input, nothing.

    function main() {
        // Enter your code here
    }
    

    update my answer

    /**
     * Typescript was corrupted and have no any codes, i was switch to Javascript
     * and copy it function to this test
     */
    function loopInvariant(ar: number[]): void {
        for (let i = 1; i < ar.length; i++) {
            var value = ar[i];
            var j = i - 1;
    
            //while (j > 0 && ar[j] > value) { // Wrong here. changes "j > 0" to "j >= 0"
            while (j >= 0 && ar[j] > value) {
                ar[j + 1] = ar[j];
                j = j - 1;
            }
            ar[j + 1] = value;
        }
        console.log(ar.join(' '));
    }
    
    function main() {
        const n: number = parseInt(readLine().trim(), 10);
    
        const arr: number[] = readLine().replace(/\s+$/g, '').split(' ').map(arrTemp => parseInt(arrTemp, 10));
    
        loopInvariant(arr);
    }