What do I have to change to implement a sort order based on code of a bubble order?

-1

My program needs to implement the selection algorithm instead of the bubble algorithm, which I have already implemented. How do I put the selection method in place of the bubble method?

import java.util.*;
public class bubble{

  public static void main(String[]args){
      Scanner entrada;
      entrada=new Scanner(System.in);
      Scanner sc=new Scanner(System.in);
      Scanner entrada2;
      entrada2=new Scanner(System.in);


      String[] nombre=new String[6];
      String auxnombre;
      int x=0;
      int y=0;
      int[] matricula= new int[6];
      int b=0;
      int a=0;
      int another=0;
      int opcion=0;
      int auxmatricula;




      do{
         a++;
         System.out.println("No. de Registro " +a);
         System.out.println("Ingresa tu numero contable");
         matricula[a]=entrada.nextInt();
         System.out.println("Ingresa tu nombre:");
         nombre[a]=sc.nextLine().toUpperCase();
         System.out.println("Deseas otro proceso? 1.si 2.no");
         another=entrada.nextInt();

         if (a>=5)
         {
            another=2;
         }
      }while(another==1);


      for(int i=1; i<5; i++)
      {
         for(y=1; y<5; y++)
         {
            if(matricula[y]>matricula[y+1])
            {
               auxmatricula=matricula[y];
               matricula[y]=matricula[y+1];
               matricula[y+1]=auxmatricula;
               auxnombre=nombre[y];
               nombre[y]=nombre[y+1];
               nombre[y+1]=auxnombre;
            }
         }
      }
      for(int i=1; i<=5; i++)
      {
         System.out.println("Numero Contable: "+matricula[i]+ "\n Nombre: "+nombre[i]);

      }

   }
}
    
asked by Stephanie B Bautista 19.01.2017 в 16:29
source

1 answer

3

To begin we re-invoke the code to take better advantage of object-oriented programming:

import java.util.*;

/**
 * @author snolde, sbautista
 *
 */
public class BubbleSort {

The fields:

    protected Scanner entrada;
    protected Scanner entrada2;
    protected String[] nombre;
    protected int[] matricula;
    protected int max;

The builder:

    public BubbleSort(int max){
        this.max=max; 
        nombre = new String[max];
        matricula = new int[max];
    };

Data entry:

    public void readData(){
        // creamos un nuevo Scanner
        entrada = new Scanner(System.in);
        entrada2 = new Scanner(System.in);
        int i = 0;
        int another=1;
        do{
            // usemos todo el arreglo, para que botar memoria?
             System.out.println("No. de Registro " +(i+1));
             System.out.println("Ingresa tu numero contable");
             matricula[i]=entrada.nextInt();
             System.out.println("Ingresa tu nombre:");
             nombre[i]=entrada2.nextLine().toUpperCase();
             // para que preguntar si no podemos ingresar mas?
             if (i<matricula.length-1){
                 //podemos aceptar otro nombre
                 System.out.println("Deseas otro proceso? 1.si 2.no");
                 another=entrada.nextInt();
             } else {
                 another = 2;
             }
            // podría ser break en vez de another=2;
             max = ++i;
        }while(another==1);
        entrada.close();
        entrada2.close();
    }

Protected methods to implement the order:

    /**
     * devuelve false si los valores cambaron de posición, true si no
     * 
     * @param a
     * @param b
     * @return
     */
    protected boolean ordenar(int a , int b){
        // si estan ordenado, nada que hacer
        if (matricula[a]<=matricula[b]) return true;
        // si no, ordenemos
        int auxInt=matricula[a];
        matricula[a]=matricula[b];
        matricula[b]=auxInt;
        String auxString=nombre[a];
        nombre[a]=nombre[b];
        nombre[b]=auxString;
        return false;
    }

    protected boolean ordenarIteracion(){
        // asumimos que la lista esta en orden
        boolean ordenado=true;
        int i=0;
        // iteración solamente hasta el penultimo elemento
        while(i<max-1){
            // ordenemos los campos y registremos si estaban ordenados, al fin incrementemos i
            ordenado = ordenar(i,1+i++) && ordenado; 
        }
        return ordenado;
    }

The method where we order everything and the sample of the result

    public void ordenar(){
        boolean ordenado;
        do{
            System.out.println("ordenando...");
            ordenado = ordenarIteracion();
        }while(!ordenado);
    }

    public void mostrarResultado(){
        for(int i=0; i<max; i++)
        {
            System.out.println("Numero Contable: "+matricula[i]+ " Nombre: "+nombre[i]);
        }
    }

and finally the main:

    public static void main(String[]args){
        BubbleSort sort = new BubbleSort(5);
        sort.readData();
        sort.ordenar();
        sort.mostrarResultado();
    }

}

and the result:

ordenando...
ordenando...
ordenando...
ordenando...
Numero Contable: 5 Nombre: STEPHANIE
Numero Contable: 11 Nombre: FULANITO
Numero Contable: 13 Nombre: CHAVO
Numero Contable: 15 Nombre: MARIANO
Numero Contable: 23 Nombre: STEFAN

Now to implement the sort order, we change only two methods:

    // cambiado: pasemos el valor start para indicar donde empezemos la busqueda para un minimo
    private boolean ordenarIteracion(int start){
        // asumimos que la lista esta en orden
        boolean ordenado=true;
        // el valor que debe tener el minimo de la iteración
        int minPos = start;

        for (int i = start+1; i<max; i++){
            // si encontramos un nuevo minimo, recordamos la posición
            if (matricula[i]<matricula[minPos]) minPos=i;
        }
            // vemos si tenemos que cambiar posiciónes
            ordenado = ordenar(start,minPos) && ordenado; 
        return ordenado;
    }

    // cambiado: 
    public void ordenar(){
        boolean ordenado;
        // solamente necesitemos iterar hasta el penultimo valor
        for (int i = 0; i<max-1 ; i++){
            ordenado = ordenarIteracion(i);
            System.out.println("ordenado..." + ordenado);
            // si la iteración terminó ordenado, estamos listo
            if (ordenado) break;
        }
    }

and we have the result:

ordenado...false
ordenado...false
ordenado...false
ordenado...false
Numero Contable: 5 Nombre: STEPHANIE
Numero Contable: 13 Nombre: CHAVO
Numero Contable: 15 Nombre: MARIANO
Numero Contable: 17 Nombre: FULANITO
Numero Contable: 23 Nombre: STEFAN

To make the matter even more entertaining, we use the BubbleSort as a superclass:

import java.util.*;

/**
 * @author snolde, sbautista
 *
 */
public class SelectionSort extends BubbleSort{


    public SelectionSort(int max){
        // usamos el constructor de la superclase
        super(max);
    };

    // cambiado: pasemos el valor start para indicar donde empezemos la busqueda para un minimo
    private boolean ordenarIteracion(int start){
        // asumimos que la lista esta en orden
        boolean ordenado=true;
        // el valor que debe tener el minimo de la iteración
        int minPos = start;

        for (int i = start+1; i<max;i++){
            // si encontramos un nuevo minimo, recordamos la posición
            if (matricula[i]<matricula[minPos]) minPos=i;
        }
            // vemos si tenemos que cambiar posiciónes
            ordenado = ordenar(start,minPos) && ordenado; 
        return ordenado;
    }

    // cambiado: 
    public void ordenar(){
        boolean ordenado;
        // solamente necesitemos iterar hasta el penultimo valor
        for (int i = 0; i<max-1 ; i++){
            ordenado = ordenarIteracion(i);
            System.out.println("ordenado..." + ordenado);
            // si la iteración terminó ordenado, estamos listo
            if (ordenado) break;
        }
    }

    public static void main(String[]args){
        SelectionSort sort = new SelectionSort(5);
        sort.readData();
        sort.ordenar();
        sort.mostrarResultado();
    }

}
    
answered by 22.01.2017 / 07:18
source