Tengo este código para ordenar por selección.
function selectionSort(array) { for(let j = 0; j < array.length; j++) { let smallest = array[j]; for(let i = j; i >= 0; i--) { if(array[i] > smallest) { let temp1 = array[i]; let temp2 = array[j]; array[i] = temp2; array[j] = temp1; } } } return array; } selectionSort([8, 5, 2, 9, 5, 6, 3]).forEach(element => { console.log(element); }); He agregado un caso de prueba, que falla. Mi idea aquí es que j es un selector de elementos, como un puntero hacia él, y el siguiente ciclo itera hacia atrás verificando los elementos anteriores e intercambiando el elemento más pequeño. ¿Pero funciona? Algunos casos de prueba como [1, 3, 2] funcionan bien, pero otros como este no
Aquí hay una guía para el algoritmo de clasificación por selección .
Su bucle externo debe estar rastreando el primer elemento sin clasificar . Técnicamente, el suyo lo es, pero está llamando al primer elemento sin ordenar smallest que no lo es.
Luego, su bucle interno debería buscar el elemento sin clasificar más pequeño e intercambiarlo con el primer elemento sin clasificar del bucle externo. Está intercambiando cada elemento más grande (en lugar del elemento más pequeño ) después del que está en i .
Hay algo fuera de lugar en su algoritmo, debería parecerse a lo siguiente.
function selectionSort(array) { for (var i = 0; i < array.length - 1; i++) { let min = i; for(var j=i+1;j<array.length;j++){ if(array[j] < array[min]) min = j; } const tmp1 = array[min] const tmp2 = array[i] array[i] = tmp1; array[min] = tmp2; } return array; } selectionSort([8, 5, 2, 9, 5, 6, 3]).forEach(element => { console.log(element); });Arreglemoslo. Como dice el algoritmo,
function selectionSort(array) { for (let j = 0; j < array.length - 1; j++) { let smallest = array[j]; let smallest_index = -1; for (let i = j + 1; i < array.length; i++) { if (array[i] <= smallest) { smallest = array[i] smallest_index = i; } } let temp1 = array[smallest_index]; let temp2 = array[j]; array[smallest_index] = temp2; array[j] = temp1; } return array; } console.log("" + selectionSort([8, 5, 2, 9, 5, 6, 3]))