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!
data.sort();and be done with it?