1

Tengo este codigo:

function num(arr) {
        var leng = arr.length,
            i, x;
    for( i = 0; i < leng; i++) {
        for( x = i + 1; x < leng; x++) {
            console.log(arr.toString())
            if (arr[i] > arr[x]) {
                a(arr, i, x);
                //console.log(arr)
            }
            
        }
    }
    return arr;
}
function a(arr, f, s) {
    var temp = arr[f];
    arr[f] = arr[s];
    arr[s] = temp;
   // console.log(arr)
}
document.getElementById("alg").innerHTML = num([8, 5, 2, 6, 9, 3, 1, 4, 0, 7]);
<h2 id="alg"></h2>

Al ejecutarlo, lo hace de forma que ordena el primer numero que encuentra, así: introducir la descripción de la imagen aquí

Y necesito que el algoritmo recorra todo el array asi:

introducir la descripción de la imagen aquí

Gracias por la ayuda.

1 respuesta 1

5

El problema es que no estás implementando correctamente el algoritmo de ordenamiento por selección

El pseudocódigo es este:

para i=0 hasta n-1
    mínimo = i;
    para j=i+1 hasta n
        si lista[j] < lista[mínimo] entonces
            mínimo = j /* (!) */
        fin si
    fin para
    intercambiar(lista[i], lista[mínimo])
fin para

Tienes que inicializar un valor mínimo (inicialmente será cero) con el que comparar los valores de tu array:

function num(arr) {       
    for(let i = 0; i < arr.length; i++) {
        let min=i;
        for(let x = i + 1; x < arr.length; x++) {            
            if (arr[min] > arr[x]) {              
                min = x;
            }            
        }
        a(arr, i, min);
    }
    return arr;
}
function a(arr, f, s) {
    console.log(arr.toString());
    var temp = arr[f];
    arr[f] = arr[s];
    arr[s] = temp;    
}

document.getElementById("alg").innerHTML = num([8, 5, 2, 6, 9, 3, 1, 4, 0, 7]);
<h2 id="alg"></h2>

Edito: Añado un ejemplo utilizando array destructuring. Con ello te ahorras la variable temp y la función a

function num(arr) {       
    for(let i = 0; i < arr.length; i++) {
        let min=i;
        for(let x = i + 1; x < arr.length; x++) {            
            if (arr[min] > arr[x]) {              
                min = x;
            }            
        }
        console.log(arr.toString());
        [arr[min],arr[i]] = [arr[i],arr[min]] 
    }
    return arr;
}
document.getElementById("alg").innerHTML = num([8, 5, 2, 6, 9, 3, 1, 4, 0, 7]);
<h2 id="alg"></h2>

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.