jeudi 18 août 2016

Why does this create an infinite loop?

This was one of my algorithm questions at FreeCodeCamp.com :


Return the lowest index at which a value (second argument) should be inserted into an array (first argument) once it has been sorted. The returned value should be a number.

If I don't put a break in my "if statement", I get a "potential infinite loop" warning. Why is that? I thought if the condition was false, the for loop would continue on to the next iteration.

//my solution

function getIndexToIns(arr, num) {
  arr.sort(function(a, b) {
    return a - b;
  });

  for (var i = 0; i < arr.length; i++) {
    if (arr[i] > num) {
    //This is the code in question
       arr.splice(i, 0, num);
       break;
    }
    else {
      arr.push(num);
    }
  }
  return arr.indexOf(num);
}

Aucun commentaire:

Enregistrer un commentaire