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;
}
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.
You can create one for yourself like the one below. Syntax for using this
let numbSet = [44,55,22,55,44,11];
Ascending by default numbSet.sorty();
Descending numbSet.sorty('dsc');
If an array of objects then pass the key like
let objSet = [{a:44},{a:55},{a:22},{a:55},{a:44},{a:11}];
objSet.sorty('asc', 'a');
let numbSet = [44, 55, 22, 55, 44, 11];
let objSet = [{
a: 44
}, {
a: 55
}, {
a: 22
}, {
a: 55
}, {
a: 44
}, {
a: 11
}];
Array.prototype.sorty = function(type, key) {
if(this.length) {
if (type === 'dsc') {
return recuDsc(this, this.length - 1, key ? key : false);
} else {
// default assending
return recuAsc(this, 0, key ? key : false);
}
}
return this;
}
function recuAsc(arry, indx, key) {
let arryLength = arry.length;
let isSmaller = false;
let a, b, i = indx + 1;
if (indx != (arryLength - 1)) {
for (i; i < arryLength; i++) {
a = arry[indx];
b = arry[i];
isSmaller = key ? a[key] < b[key] : a < b;
if (!isSmaller) {
arry[indx] = b;
arry[i] = a;
}
}
recuAsc(arry, indx + 1, key ? key : false);
}
return arry;
}
function recuDsc(arry, indx, key) {
let arryLength = arry.length;
let isSmaller = false;
let a, b, i = indx - 1;
if (indx != (0)) {
for (i; i >= 0; i--) {
a = arry[indx];
b = arry[i]
isSmaller = key ? a[key] < b[key] : a < b;
if (!isSmaller) {
arry[indx] = b;
arry[i] = a;
}
}
recuDsc(arry, indx - 1, key ? key : false);
}
return arry;
}
console.log('Sorty an Array of numbers, ascending');
console.log(numbSet.sorty());
console.log('Sorty an Array of numbers, descending');
console.log(numbSet.sorty('dsc'));
console.log('Sorty an Array of Object');
console.log(objSet.sorty('asc', 'a'))