We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Correctness and the Loop Invariant
Correctness and the Loop Invariant
+ 0 comments Java 8 Easy Solution:
public static void insertionSort(int[] A){ Arrays.sort(A); printArray(A); }
+ 0 comments Java 8:
public static void insertionSort(int[] A){ for(int i = 0; i < A.length; i++){ for(int j = i+1; j < A.length; j++){ if(A[j]<=A[i]){ int temp = A[i]; A[i]=A[j]; A[j]= temp; } } } printArray(A); }
+ 0 comments For javascript coders, I submitted an edit to complete and fix the initial code, if it is still wrong use this as starting point, and remember this challenge is not about fixing the insertionSort function only but also learning the loop Invariant concept and applying it to the problem Note The Solution at the end
'use strict'; const fs = require('fs'); process.stdin.resume(); process.stdin.setEncoding('utf-8'); let inputString = ''; let currentLine = 0; process.stdin.on('data', function(inputStdin) { inputString += inputStdin; }); process.stdin.on('end', function() { inputString = inputString.split('\n'); main(); }); function readLine() { return inputString[currentLine++]; } /** * Add function here to find the bug in the insertionSort function. */ function insertionSort(n, arr) { for(let i = 0; i < arr.length; i++){ let value = arr[i]; let j = i - 1; while(j > 0 && arr[j] > value){ arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = value; } console.log(arr.join().replaceAll(",", " ")); } function main() { const n = parseInt(readLine().trim(), 10); const arr = readLine().replace(/\s+$/g, '').split(' ').map(arrTemp => parseInt(arrTemp, 10)); insertionSort(n, arr); }
Solution
function isSorted(arr) { const clone = [...arr].sort((a, b) => a > b); if(clone.toString() === arr.toString()) { return true; } else { clone.map((num, idx) => { if(num !== arr[idx]) { console.log(`Sort Failed at index: ${idx}`) } }) } } // Add the to insertionSort function if(isSorted(arr)) { console.log(arr.join().replaceAll(",", " ")); }
+ 0 comments C++ solution, just while loop constraints fixed.
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 && arr[j]>value) { 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 import java.util.Scanner; class Solution{ public static void main(String [] agrs){ Scanner sc = new Scanner(System.in); int a = sc.nextInt(); int temp=0; int arr[] = new int[10000]; for(int i=0;i<a;i++) arr[i] = sc.nextInt(); for(int i=0;i<a;i++){ for(int j=i+1;j<a;j++){ if(arr[i]>arr[j]){ temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } } for(int i=0;i<a;i++) System.out.print(arr[i]+" "); } }
Load more conversations
Sort 166 Discussions, By:
Please Login in order to post a comment