Introducción al ordenamiento por selección en Java

Selección Ordenar en Java es un método de clasificación que encuentra continuamente el elemento más pequeño en la parte no ordenada y lo mantiene al principio (para ordenar en orden ascendente). El proceso se repetirá hasta que se ordene la matriz de entrada. Además, en Selección de selección, dividiremos la matriz de entrada en dos submatrices donde una matriz se usa para elementos ordenados y otra matriz para elementos no clasificados. Al principio, no habrá elementos en la subcadena ordenada. Veamos el funcionamiento del orden de selección en detalle en la siguiente sección.

Cómo funciona la selección de selección en Java

La ordenación por selección funciona de una manera simple donde mantiene dos submatrices de la matriz de entrada. Son:

  • Subarreglo ordenado para mantener los elementos ordenados
  • Subarreglo sin clasificar para mantener los elementos sin clasificar.

Algoritmo:

El siguiente es el algoritmo que se utiliza para la selección de selección

  1. Establezca el puntero mínimo (MIN) en la ubicación 0.
  2. Encuentre el elemento más pequeño de la lista de elementos en la matriz
  • Intercambie el elemento mínimo con la ubicación 0
  1. Mueva el puntero MIN a la siguiente posición
  2. Repita el proceso hasta que se ordene la matriz de entrada.

Comprendamos el tipo de selección con un ejemplo. A continuación se muestra la matriz de entrada que debe clasificarse. Los elementos en color azul negrita serán parte de la matriz ordenada.

Paso 1 : establezca el puntero MIN en la primera ubicación. Entonces, el puntero MIN apunta a 15.

Más pequeño: = 15

Paso 2 : Encuentra el elemento más pequeño comparándolo con el resto de los elementos. Comparando 15 y 21, 15 es el más pequeño. Entonces, el más pequeño no cambiará en este caso.

Más pequeño: = 15

Comparando 15 y 6, 6 es el más pequeño.

Más pequeño: = 6

Comparando 6 y 3, 3 es el más pequeño.

Más pequeño: = 3

3 también será más pequeño en este caso, ya que 19 es mayor que 3.

Más pequeño: = 3

Más pequeño: = 3

Finalmente, en esta iteración, se encuentra que 3 es el más pequeño.

Paso 3 : intercambia el elemento más pequeño con el elemento en la ubicación 0.

Paso 4: Incremente el puntero MIN a la siguiente posición.

Paso 5: Encuentra el siguiente elemento más pequeño comparándolo con el resto de los elementos.

Más pequeño: = 21

Más pequeño: = 6

Más pequeño: = 6

Más pequeño: = 6

Más pequeño: = 6

Paso 6: intercambie el elemento más pequeño con el elemento en la ubicación 1.

Repita el proceso hasta que se forme una matriz ordenada como se muestra a continuación.

Ejemplos para implementar el orden de selección en Java

Como ya se mencionó anteriormente, el orden de selección se basa en encontrar el mínimo y el intercambio. Ahora, veamos cómo implementar la selección mediante Java.

Programa Java para ordenar los elementos en una matriz usando Selección Ordenar

import java.util.*;
public class SelSortExample (
//Method that implements Selectionsort
public static void selsort(int() arr)
(
int n=arr.length; //length of the array
for(int i=0;i (
int MIN=i; //set the first position as minimum
System.out.println("Sorting based on Number "+(i+1));
//Find the smallest element by comparing with the element in MIN position
for(int j=i+1;j (
System.out.println("Comparing "+ arr(MIN) + " and " + arr(j));
if(arr(j) (
System.out.println(arr(MIN) + " is greater than " + arr(j) );
MIN=j;
)
)
//Swap the smallest element with element in MIN position
int temp=arr(i);
arr(i)=arr(MIN);
arr(MIN)=temp;
)
)
public static void main(String() args) (
int() arr= (15, 21, 6, 3, 19, 20); // input array
System.out.println("Elements in the array before Sorting: "+ Arrays. toString (arr));
selsort (arr);//calling the selection sort method
System.out.println("Elements in the array after Sorting: "+Arrays. toString (arr));
)
)
import java.util.*;
public class SelSortExample (
//Method that implements Selectionsort
public static void selsort(int() arr)
(
int n=arr.length; //length of the array
for(int i=0;i (
int MIN=i; //set the first position as minimum
System.out.println("Sorting based on Number "+(i+1));
//Find the smallest element by comparing with the element in MIN position
for(int j=i+1;j (
System.out.println("Comparing "+ arr(MIN) + " and " + arr(j));
if(arr(j) (
System.out.println(arr(MIN) + " is greater than " + arr(j) );
MIN=j;
)
)
//Swap the smallest element with element in MIN position
int temp=arr(i);
arr(i)=arr(MIN);
arr(MIN)=temp;
)
)
public static void main(String() args) (
int() arr= (15, 21, 6, 3, 19, 20); // input array
System.out.println("Elements in the array before Sorting: "+ Arrays. toString (arr));
selsort (arr);//calling the selection sort method
System.out.println("Elements in the array after Sorting: "+Arrays. toString (arr));
)
)
import java.util.*;
public class SelSortExample (
//Method that implements Selectionsort
public static void selsort(int() arr)
(
int n=arr.length; //length of the array
for(int i=0;i (
int MIN=i; //set the first position as minimum
System.out.println("Sorting based on Number "+(i+1));
//Find the smallest element by comparing with the element in MIN position
for(int j=i+1;j (
System.out.println("Comparing "+ arr(MIN) + " and " + arr(j));
if(arr(j) (
System.out.println(arr(MIN) + " is greater than " + arr(j) );
MIN=j;
)
)
//Swap the smallest element with element in MIN position
int temp=arr(i);
arr(i)=arr(MIN);
arr(MIN)=temp;
)
)
public static void main(String() args) (
int() arr= (15, 21, 6, 3, 19, 20); // input array
System.out.println("Elements in the array before Sorting: "+ Arrays. toString (arr));
selsort (arr);//calling the selection sort method
System.out.println("Elements in the array after Sorting: "+Arrays. toString (arr));
)
)
import java.util.*;
public class SelSortExample (
//Method that implements Selectionsort
public static void selsort(int() arr)
(
int n=arr.length; //length of the array
for(int i=0;i (
int MIN=i; //set the first position as minimum
System.out.println("Sorting based on Number "+(i+1));
//Find the smallest element by comparing with the element in MIN position
for(int j=i+1;j (
System.out.println("Comparing "+ arr(MIN) + " and " + arr(j));
if(arr(j) (
System.out.println(arr(MIN) + " is greater than " + arr(j) );
MIN=j;
)
)
//Swap the smallest element with element in MIN position
int temp=arr(i);
arr(i)=arr(MIN);
arr(MIN)=temp;
)
)
public static void main(String() args) (
int() arr= (15, 21, 6, 3, 19, 20); // input array
System.out.println("Elements in the array before Sorting: "+ Arrays. toString (arr));
selsort (arr);//calling the selection sort method
System.out.println("Elements in the array after Sorting: "+Arrays. toString (arr));
)
)

Salida de muestra:

En el programa anterior, tenemos dos métodos: métodos principales y método de venta. El método principal llama al método de clasificación de venta pasando la matriz de entrada como argumento. El elemento mínimo será identificado e intercambiado con el elemento señalado por MIN.

El orden de selección también se puede usar cuando la matriz de entrada no está definida en el código. Veamos cómo funciona usando el siguiente programa.

Programa Java para ordenar los elementos usando selección Ordenar

import java.util.*;
public class SelectionSortExample
(
public static void main(String args())
(
int n, i, j, tempvar;
Scanner sc = new Scanner(System.in); //To take the input from user
System.out.print("Enter the size of array : \n");
n = sc.nextInt();
int array() = new int(n); //initialising the array
System.out.print("Enter the elements that need to be inserted in the array : \n");
//inserting the elements to the array
for(i=0; i (
array(i) = sc.nextInt();
)
System.out.print("array before Sorting: \n"+ Arrays.toString(array));
System.out.print("\nSorting begins here..\n");
for(i=0; i (
for(j=i+1; j (
if(array(i) > array(j))
(
tempvar = array(i);
array(i) = array(j);
array(j) = tempvar;
)
)
)
System.out.print("Array after Sorting is :\n");
for(i=0; i (
System.out.print(array(i)+ " ");
)
)
)
import java.util.*;
public class SelectionSortExample
(
public static void main(String args())
(
int n, i, j, tempvar;
Scanner sc = new Scanner(System.in); //To take the input from user
System.out.print("Enter the size of array : \n");
n = sc.nextInt();
int array() = new int(n); //initialising the array
System.out.print("Enter the elements that need to be inserted in the array : \n");
//inserting the elements to the array
for(i=0; i (
array(i) = sc.nextInt();
)
System.out.print("array before Sorting: \n"+ Arrays.toString(array));
System.out.print("\nSorting begins here..\n");
for(i=0; i (
for(j=i+1; j (
if(array(i) > array(j))
(
tempvar = array(i);
array(i) = array(j);
array(j) = tempvar;
)
)
)
System.out.print("Array after Sorting is :\n");
for(i=0; i (
System.out.print(array(i)+ " ");
)
)
)
import java.util.*;
public class SelectionSortExample
(
public static void main(String args())
(
int n, i, j, tempvar;
Scanner sc = new Scanner(System.in); //To take the input from user
System.out.print("Enter the size of array : \n");
n = sc.nextInt();
int array() = new int(n); //initialising the array
System.out.print("Enter the elements that need to be inserted in the array : \n");
//inserting the elements to the array
for(i=0; i (
array(i) = sc.nextInt();
)
System.out.print("array before Sorting: \n"+ Arrays.toString(array));
System.out.print("\nSorting begins here..\n");
for(i=0; i (
for(j=i+1; j (
if(array(i) > array(j))
(
tempvar = array(i);
array(i) = array(j);
array(j) = tempvar;
)
)
)
System.out.print("Array after Sorting is :\n");
for(i=0; i (
System.out.print(array(i)+ " ");
)
)
)
import java.util.*;
public class SelectionSortExample
(
public static void main(String args())
(
int n, i, j, tempvar;
Scanner sc = new Scanner(System.in); //To take the input from user
System.out.print("Enter the size of array : \n");
n = sc.nextInt();
int array() = new int(n); //initialising the array
System.out.print("Enter the elements that need to be inserted in the array : \n");
//inserting the elements to the array
for(i=0; i (
array(i) = sc.nextInt();
)
System.out.print("array before Sorting: \n"+ Arrays.toString(array));
System.out.print("\nSorting begins here..\n");
for(i=0; i (
for(j=i+1; j (
if(array(i) > array(j))
(
tempvar = array(i);
array(i) = array(j);
array(j) = tempvar;
)
)
)
System.out.print("Array after Sorting is :\n");
for(i=0; i (
System.out.print(array(i)+ " ");
)
)
)
import java.util.*;
public class SelectionSortExample
(
public static void main(String args())
(
int n, i, j, tempvar;
Scanner sc = new Scanner(System.in); //To take the input from user
System.out.print("Enter the size of array : \n");
n = sc.nextInt();
int array() = new int(n); //initialising the array
System.out.print("Enter the elements that need to be inserted in the array : \n");
//inserting the elements to the array
for(i=0; i (
array(i) = sc.nextInt();
)
System.out.print("array before Sorting: \n"+ Arrays.toString(array));
System.out.print("\nSorting begins here..\n");
for(i=0; i (
for(j=i+1; j (
if(array(i) > array(j))
(
tempvar = array(i);
array(i) = array(j);
array(j) = tempvar;
)
)
)
System.out.print("Array after Sorting is :\n");
for(i=0; i (
System.out.print(array(i)+ " ");
)
)
)

Salida de muestra:

Aquí, los elementos de entrada proporcionados por el usuario se compararán con la variable temporal y se intercambiarán. El proceso se repetirá hasta que se forme una matriz ordenada.

Rendimiento del orden de selección

Esta técnica de clasificación se utiliza por su simplicidad y ciertas otras ventajas de rendimiento sobre otras técnicas de clasificación más.

Conclusión

El orden de selección no funciona de manera eficiente en listas grandes, ya que consume más tiempo para la comparación. La ordenación por selección es un método en el que una matriz de entrada se dividirá en dos submatrices para mantenerlos ordenados y sin clasificar. El elemento mínimo en la matriz se intercambiará con el elemento en la primera posición y el proceso continuará hasta que se forme una matriz ordenada.

Artículos recomendados

Esta es una guía para la selección Ordenar en Java. Aquí discutimos la Introducción, el trabajo y el rendimiento de la selección de selección junto con algunos ejemplos. También puede consultar los siguientes artículos para obtener más información:

  1. Combinar Ordenar en Java
  2. Heap Ordenar en Java
  3. Copiar constructor en Java
  4. Patrones de estrellas en Java
  5. Heap Sort en Python

Categoría: