While loop needs extra condition

inside the while loop if i don’t include the if(j>0) , it breaks on the first cycle, saying ‘cannot set properties of undefined’. But the while loop doesn’t initiate when j is below 1 anyway. which i can check with the console.log. So don’t understand why it won’t just perform the ‘swap’.

  **Your code so far**

function insertionSort(arr) {
let result=[]
for(let i=0;i<arr.length;i++){
  result.push(arr[i])
  let element=result[i]
  let j=i
  while (element<result[j-1]) {
    console.log('j=',j,' j-1=',j-1)
    if(j>0)[ result[j-1], result[j] ] = [ result[j], result[j-1] ]
    j--
  }
}
return result;
}
console.log(insertionSort([5,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92]))
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.61 Safari/537.36

Challenge: Implement Insertion Sort

Link to the challenge:

[quote=“ugwen, post:1, topic:511861”]

let result=[]
for(let i=0;i<arr.length;i++){
  result.push(arr[i])
  let element=result[i]
  let j=i
  while (element<result[j-1]) {
    console.log('j=',j,' j-1=',j-1)
    if(j>0)[ result[j-1], result[j] ] = [ result[j], result[j-1] ]
    j--
  }
}
return result

hello and welcome to fcc forum :slight_smile:
can you not use “map / sort” array method in that “insertionSort()”

not sort at least. we are to avoid provided funtions. i already figured out a better way, it’s just this point botherss me.

as in compare and replace?

yes, thats wat it is. i just happen to create a new array here. i know how to correct that tho.

What is 0-1?

that’s got me really confused.

  • firstly trying to figure out where i had ‘0-1’.
  • then i realized element<result[j-1] equates to true when result[j-1]=undefined (unintended).

then i realised it works fine without the logs:

while (element<result[j-1]) {
    // console.log('j=',j,' j-1=',j-1)
    [ result[j-1], result[j] ] = [ result[j], result[j-1] ]
    j--
  }

weird

console.log should not cause any problem in code!! unless it breaks it’s enclosing element syntax

2 Likes

You still need to account for your bounds on j somehow. result[-1] isn’t defined.

yes, i can see good practice would be to avoid result[-1] ahead of the while loop. still a weird behaviour with the logs affecting it, but i’ll put it down to that oversight and move on. thanks.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.