Correctness and the Loop Invariant

Sort by

recency

|

197 Discussions

|

  • + 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);
    }
    
  • + 0 comments

    Here is my c++ solution, you can watch the explanation here : https://youtu.be/G0rl1U-fDRY

    void insertionSort(int N, int arr[]) {
        int i,j;
        int value;
        for(i=1;i<N;i++)
        {
            value=arr[i];
            j=i-1;
            while(j>=0 && value<arr[j])
            {
                arr[j+1]=arr[j];
                j=j-1;
            }
            arr[j+1]=value;
        }
        for(j=0;j<N;j++)
        {
            printf("%d",arr[j]);
            printf(" ");
        }
    }
    
  • + 0 comments

    C++ 20 and C++14 code came empty. C++ 11 is Ok

  • + 0 comments

    while(j>=0 && value

  • + 0 comments

    java

    public static void insertionSort(int[] A) {

        Arrays.sort(A);
    
        printArray(A);
    

    } }