Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sorting an array in descending order in javascript without using any built-in method

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;
}
like image 831
Mary Avatar asked Sep 26 '26 08:09

Mary


1 Answers

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.

like image 64
trincot Avatar answered Sep 27 '26 23:09

trincot