Skip to content
the poor coder

ordenar un array de mayor a menor

Poor Man
Published
Reading time
2 min read
On this page

Ordenar un array de mayor a menor#

Ordenar un array de mayor a menor es una tarea común en la programación. Hay varios métodos para hacerlo, pero los más comunes son "Bubble Sort" y "Quick Sort".

Bubble Sort#

El ordenamiento burbuja o bubble sort es uno de los algoritmos de ordenamiento más simples y conocidos. Se llama así porque los elementos más grandes "burbujean" hacia arriba a medida que se ordenan.

JavaScript

const array = [5, 3, 8, 4, 2];
let aux;

for(let i = 0; i < array.length; i++){
    for(let j = 0; j < array.length-1; j++){
        if(array[j] < array[j+1]){
            aux = array[j];
            array[j] = array[j+1];
            array[j+1] = aux;
        }
    }
}

console.log(array); // Output: [8, 5, 4, 3, 2]

Quick Sort#

El ordenamiento rápido o quick sort es un algoritmo de ordenamiento recursivo y divide y vencerás. Funciona dividiendo la lista en sub-listas más pequeñas y luego ordenando esas sub-listas repetidamente hasta que toda la lista esté ordenada.

JavaScript

const array = [5, 3, 8, 4, 2];

function quickSort(array) {
    if (array.length <= 1) {
        return array;
    } else {
        let left = [];
        let right = [];
        let newArray = [];
        let pivot = array.pop();
        let length = array.length;

        for (let i = 0; i < length; i++) {
            if (array[i] <= pivot) {
                left.push(array[i]);
            } else {
                right.push(array[i]);
            }
        }

        return newArray.concat(quickSort(left), pivot, quickSort(right));
    }
}

console.log(quickSort(array)); // Output: [8, 5, 4, 3, 2]

En resumen, hay muchas formas de ordenar un array de mayor a menor, pero los dos métodos más comunes son bubble sort y quick sort. Bubble sort es más fácil de entender y escribir, pero puede ser lento en arrays grandes. Quick sort es más rápido en arrays grandes, pero puede ser más difícil de entender y escribir.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC