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.
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
'usestrict';constfs=require('fs');process.stdin.resume();process.stdin.setEncoding('utf-8');letinputString='';letcurrentLine=0;process.stdin.on('data',function(inputStdin){inputString+=inputStdin;});process.stdin.on('end',function(){inputString=inputString.split('\n');main();});functionreadLine(){returninputString[currentLine++];}/** * Add function here to find the bug in the insertionSort function. */functioninsertionSort(n,arr){for(leti=0;i<arr.length;i++){letvalue=arr[i];letj=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(","," "));}functionmain(){constn=parseInt(readLine().trim(),10);constarr=readLine().replace(/\s+$/g,'').split(' ').map(arrTemp=>parseInt(arrTemp,10));insertionSort(n,arr);}
Solution
functionisSorted(arr){constclone=[...arr].sort((a,b)=>a>b);if(clone.toString()===arr.toString()){returntrue;}else{clone.map((num,idx)=>{if(num!==arr[idx]){console.log(`SortFailedatindex:${idx}`)}})}}// Add the to insertionSort functionif(isSorted(arr)){console.log(arr.join().replaceAll(","," "));}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Correctness and the Loop Invariant
You are viewing a single comment's thread. Return to all 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
Solution