2

For fun, I started some JavaScript on CheckiO. With the median task I got a problem. First I tried to sort the given array with a for loop. To see the array during the loop I used a console.log.

for (var i = 0; i < data.length-1; i++) {
    if (data[i] > data[i+1]) {
        var temp = data[i];
        data[i] = data[i+1];
        data[i+1] = temp;
        i = 0;
    }
    console.log(data);
}

The problem is when there is only one number in the wrong position; the sorting stops and just prints out the array a few times. For example:

median([5,4,3,2,1])
[ 4, 5, 3, 2, 1 ]
[ 4, 3, 5, 2, 1 ]
[ 4, 3, 5, 2, 1 ]
[ 4, 3, 2, 5, 1 ]
[ 4, 2, 3, 5, 1 ]
[ 4, 2, 3, 5, 1 ]
[ 4, 2, 3, 5, 1 ]
[ 4, 2, 3, 1, 5 ]
[ 4, 2, 3, 1, 5 ]
[ 4, 2, 1, 3, 5 ]
[ 4, 1, 2, 3, 5 ]
[ 4, 1, 2, 3, 5 ]
[ 4, 1, 2, 3, 5 ]
[ 4, 1, 2, 3, 5 ]

Is there any explanation for this behavior? Thanks!

4
  • You should look at developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…. Commented Jul 18, 2017 at 19:21
  • Does the sort need to be hand-rolled or can you use data.sort(); and be done with it? Commented Jul 18, 2017 at 19:28
  • I revised a bit of my answer to make sure you understand and can see how your code and mine differ. I think your idea for a sorting loop this way is simple and nice but it needed a little debugging help to get it to the finish line. I hope my answer provides not just the solution but also a way for you to understand for yourself how you can see your mistake in the console and become better at debugging. Commented Jul 18, 2017 at 19:39
  • idnamzciv, please select an answer. Plenty of great solutions have been offered and by my tests, all will provide a suitable solution. Commented Aug 3, 2017 at 19:35

4 Answers 4

1

There is a great sort function implemented for you on JavaScripts Array prototype object.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

However, I'm betting you know this and are implementing this code for learning purposes.

The bug in your version relates to the incrementing of this variable i

Instead, try this:

var i = 0;
while(i < data.length) {
  if(data[i] > data[i + 1]) {
    var temp = data[i];
    data[i] = data[i + 1];
    data[i + 1] = temp;
    i = 0;
    continue;
  }

  i += 1;
}

Since we do not know the required number of iterations, it's more appropriate and clear to use a while loop instead of the for loop. This way, the code is clear and the incrementing of i is only done when the logical if statement evaluates to false.

Sign up to request clarification or add additional context in comments.

1 Comment

I like what you did with this solution. In my version I set the i = -1 but the continue actually handles it quite well and if you are having your code worked on by multiple users might make more sense without the need for a comment to make sure someone does not break your work. Nicely done.
0

your code is failing because even though you make i=0 in if block, after iteration is finished i gets incremented and becomes 1, so it never checks for data[0] again. you can do something like this:

var data = [5,4,3,2,1];

for(var i = 0; i < data.length;) {
  if(data[i]>data[i+1]) {
      var temp = data[i];
      data[i] = data[i+1];
      data[i+1] = temp;
      i = 0;
  }else{
      i++;
  }
  console.log(data);
}

Comments

0

var a =[ 4, 5, 3, 2, 1 ];
var b =[ 4, 3, 5, 1, 2 ];
var c =[ 5, 3, 4, 2, 1 ];


function mySort(inArray) {
    return inArray.sort(function(x,y) { return x>y ? 1 : -1});
}

console.log( mySort(a) );
console.log( mySort(b) );
console.log( mySort(c) );

is this what you are looking for?

Comments

0

The code you wrote looks fine except that it does not check for the first element due to the loop iteration adding +1 to the i value.

To fix this, just set your i = -1; instead of i = 0;.

median([5,4,3,2,1]);

function median(data) {
  for(var i = 0; i < data.length-1; i++) {
  		//console.log(i, data[i], data[i+1], data);
      if(data[i]>data[i+1]) {
          var temp = data[i];
          data[i] = data[i+1];
          data[i+1] = temp;
          i=-1; // Reset iterator so it is back to 0 on the next loop.
      }
      console.log(data);
  }
}

EDIT: I added a commented out line of code to the snippet. If you uncomment it and comment the other console.log, you will get outputs to the console that show you the index you're at, the value of that index, the value at the index you're comparing it to and then the current state of the array. Try changing the -1 to 0 and look at how it differs from having it reset to -1.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.