La ordenación por selección busca el valor más pequeño en la parte pendiente y lo pone en la siguiente posición libre. Tras cada pasada queda un valor más en su posición definitiva. Aquí cada par de posiciones se compara una vez. En total son n(n − 1)/2 comparaciones, incluso si los datos ya están ordenados.
Ejemplo sencillo
Seleccione 1 para la primera posición y luego 2 para la segunda. Imprima la secuencia ordenada.
Al empezar3 1 2
Resultado1 2 3
Main.java
public class Main {
public static void main(String[] args) {
int[] values = {3, 1, 2};
int i = 0;
while (i < 2) {
int smallest = i;
int j = i + 1;
while (j < 3) {
if (values[j] < values[smallest]) {
smallest = j;
}
j += 1;
}
int saved = values[i];
values[i] = values[smallest];
values[smallest] = saved;
i += 1;
}
i = 0;
while (i < 3) {
System.out.println(values[i]);
i += 1;
}
}
}
Salida
1
2
3
Ejemplos de la vida diaria
Cargar primero los paquetes más ligeros
Las parcelas pesan 8, 3 y 5 kilogramos. ¿Cuál debería ocupar la primera posición de carga?
Al empezar8 3 5
Resultado3 8 5
Escanear los tres, luego cambiar 3 con el paquete en el frente.
Elegir la fecha más temprana
Los formularios no variados muestran los días 9, 12 y 4. ¿Qué fecha va en la primera bandeja?
Al empezar9 12 4
Resultado4
La lectura de las dos primeras fechas por sí sola perdería el día 4.
Ordenar un estante sin sacar los objetos a otro sitio
Los libros 1 y 2 ya están fijos. Sólo quedan los libros 5 y 3. ¿Qué sección necesita escanear?
Al empezar1 2 • 5 3
Resultado1 2 3 5
Deja el prefijo fijo solo. Seleccione 3 del par restante y muévalo a su lugar.
Coste y límites
Selection sort recorre los elementos restantes incluso cuando ya están en orden. Utiliza O(n²) comparaciones y como máximo n−1 intercambios.
Complejidad temporal
Mejor caso: Θ(n²)
Caso promedio: Θ(n²)
Peor caso: Θ(n²)
Ordenación por selección en Java
Código fuente en Java
class SelectionSortExample {
public void selectionSort(int[] arr) {
int length = arr.length;
for(int i = 0; i < length - 1; i++) {
int minIndex = i;
for(int j = i + 1; j < length; j++) {
if(arr[minIndex] > arr[j]) {
minIndex = j;
}
}
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
public void printArray(int[] arr) {
for(int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println("");
}
public static void main(String[] args) {
SelectionSortExample obj = new SelectionSortExample();
int[] arr = { 15, 3, 12, 6, -9, 9, 0 };
System.out.print("Before Sorting: ");
obj.printArray(arr);
obj.selectionSort(arr);
System.out.print("After Sorting: ");
obj.printArray(arr);
}
}
Salida
Before Sorting: 15 3 12 6 -9 9 0
After Sorting: -9 0 3 6 9 12 15
Anuncios
Sigue el ejemplo paso a paso
Empieza con [15, 3, 12, 6, -9, 9, 0].
Empieza en el índice 0. Escanee los valores restantes y recuerde la posición del valor más pequeño, −9.
Intercambio −9 con el primer valor, 15. La primera posición es ahora definitiva.
Repita desde la siguiente posición. Cuando sólo queda un valor, toda la matriz está ordenada.
Ordenación por selección en Java paso a paso
Código fuente en Java
class SelectionSortExample {
public void selectionSort(int[] arr) {
// Get the length of an array
int length = arr.length;
// Loop all the element in an array except the last element
for(int i = 0; i < length - 1; i++) {
int minIndex = i;
// Find an index of a lowest element in the right-hand side
// corresponding to the element arr[i].
for(int j = i + 1; j < length; j++) {
if(arr[minIndex] > arr[j]) {
minIndex = j;
}
}
// Swap the lowest element with the current element (i.e. arr[i] <=> arr[minIndex])
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
public void printArray(int[] arr) {
// Loop the item and print each item in the console with white space seperated
for(int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println("");
}
public static void main(String[] args) {
SelectionSortExample obj = new SelectionSortExample();
int[] arr = { 15, 3, 12, 6, -9, 9, 0 };
System.out.print("Before Sorting: ");
obj.printArray(arr);
obj.selectionSort(arr);
System.out.print("After Sorting: ");
obj.printArray(arr);
}
}
Salida
Before Sorting: 15 3 12 6 -9 9 0
After Sorting: -9 0 3 6 9 12 15