add asc/desc

This commit is contained in:
lucaspalomodevelop 2022-03-03 19:16:40 +01:00
parent 6266a05dd1
commit 842196398e
2 changed files with 11 additions and 3 deletions

View File

@ -1,10 +1,10 @@
function bubblesort(array) {
function bubblesort(array, asc = true) {
let swap;
let sorted;
do {
sorted = true;
for (let i = 0; i < array.length; i++) {
if (array[i] > array[i + 1]) {
if (getAscExpression(array[i], array[i + 1], asc)) {
swap = array[i];
array[i] = array[i + 1];
array[i + 1] = swap;
@ -15,4 +15,12 @@ function bubblesort(array) {
return array;
}
function getAscExpression(first, secound, asc) {
if (asc) {
return first > secound;
} else {
return secound > first;
}
}
module.exports = bubblesort;

View File

@ -1,3 +1,3 @@
let bubblesort = require("./bubblesort");
console.log(bubblesort([1, 3, 2]));
console.log(bubblesort([1, 3, 2], true));