I don't know why the code skips some numbers some times. For case 4: a: [4, 2, 9, 11, 2, 16]
my output is [2, 4, 2, 9, 11, 16]
when the expected output is [2, 2, 4, 9, 11, 16]
.
I'm not modifying the index array so it should check every number position's. Also, I'm not sure how line 7 completely works, in position j it's added the elimination of the element i? If so why is there an [0] behind?
I find this code kind of messy but I need to learn from it.
function sortByHeight(a) {
r = a
for(i = 0; i < a.length; i++) {
if (a[i]!= -1) {
for(j = 0; j < a.length; j++) {
if (a[j] != -1 && a[i] - a[j] < 0) {
r.splice(j,0,r.splice(i,1)[0])
}
}
}
}
return r
}