I need to sort a simple array in descending order in javaScript without using a built-in method and it took me way too much time already... please help
function dscSort(array) {
for (var i = 1; i < array.length; i++) {
var tmp = array[i];
for (var j = i - 1; j >= 0 && (array[j] < array[i]); j--) {
array[j + 1] = array[j];
}
array[j + 1] = tmp;
}
return array;
}
The approach is correct. You just had a tiny bug in the code. Instead of this:
for (var j = i - 1; j >= 0 && (array[j] < array[i]); j--) {
Do this:
for (var j = i - 1; j >= 0 && (array[j] < tmp); j--) {
This is necessary, because the value at array[i] might get overwritten with array[i-1] at the first iteration, and so in the next iteration you would be looking at the wrong value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With