Viruz Blog
¿Quieres reaccionar a este mensaje? Regístrate en el foro con unos pocos clics o inicia sesión para continuar.

Métodos de ordenamiento

Ir abajo

Métodos de ordenamiento Empty Métodos de ordenamiento

Mensaje  Admin (Viruz) Mar Ene 08, 2013 3:30 am

Hemos conocido a lo largo de este tiempo varios métodos de ordenamiento al igual en donde podemos aplicarlos y como realizarlos, si en dado caso desean conocer alguno de los métodos que se han hecho en el blog mas adelante podrán apreciar los enlaces. Mientras veremos un programa visual en el cual integran varias métodos de ordenamiento a la vez.
Imagen
[Tienes que estar registrado y conectado para ver esa imagen]

Lo que se necesita conocer
  • Ordenamiento de cadenas (burbuja).
  • Ordenamiento QuickSort.
  • Método de la burbuja.
Se debe conocer que existen muchos métodos existentes con los cuales uno puede ordenar cadenas (estructura de datos) en este ejemplo se verán los siguientes en un solo programa:

  • Burbuja.
  • Búsqueda Secuencial.
  • Shell Sort.
  • Radix Sort.
Nota: Antes de explicar debo decir que los métodos shell y radix los encontré en la web y los integre a mi programa así que pueden existir otros mejores.

¿Como funciona el programa?

  1. El primer paso es crear el diseño de la ventana en el caso de este ejemplo se crearon dentro 2 paneles que contiene los métodos de ordenamiento y las opciones del vector.
  2. Con el componente JRadioButton se elabora el primer panel donde estos solo tendrán el evento de asignarse un número para identificar en un Swicth - Case.
  3. El botón (JButton) es el que tiene la lógica para ejecutar los métodos para ello se debe instanciar la clase MetodosOrdenamiento en el constructor y así mandar a llamar los métodos.
  4. Por último en esta clase se tienen 2 arreglos llenados de manera estática o implícitamente como también se le conoce en el cual siempre se va a mostrar el llamado arr el otro se ocupa para las diferentes opciones como copiar, eliminar e insertar.
Código

Clase Ventana
Código:
import javax.swing.ButtonGroup;
import javax.swing.JOptionPane;

/**
 *
 * @author Viruz
 */
public class Ventana extends javax.swing.JFrame {

    /**
    * Creates new form Ventana
    */
    private MetodosOrdenamiento metodos;
    private int opc;

    public Ventana() {
        initComponents();
        metodos = new MetodosOrdenamiento();


        ButtonGroup grupoRadio = new ButtonGroup();
        //Adición a grupo de botones
        grupoRadio.add(jRadioButton1);
        grupoRadio.add(jRadioButton2);
        grupoRadio.add(jRadioButton3);
        grupoRadio.add(jRadioButton4);
    }

    /**
    * This method is called from within the constructor to initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is always
    * regenerated by the Form Editor.
    */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();
        jButton2 = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jRadioButton2 = new javax.swing.JRadioButton();
        jRadioButton3 = new javax.swing.JRadioButton();
        jRadioButton1 = new javax.swing.JRadioButton();
        jRadioButton4 = new javax.swing.JRadioButton();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Viruz Blog: Métodos de Ordenamiento");
        setAutoRequestFocus(false);

        jPanel1.setLayout(new java.awt.BorderLayout());

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Opciones de vector:"));

        jList1.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Mostrar Vector", "Insertar nuevo valor", "Eliminar Número", "Salir" };
            public int getSize() {
                return strings.length;
            }
            public Object getElementAt(int i) {
                return strings[i];
            }
        });
        jScrollPane1.setViewportView(jList1);

        jButton2.setText("Aceptar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

jPanel1.add(jPanel2, java.awt.BorderLayout.CENTER);

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Método de Ordenamiento:"));
        jPanel3.setPreferredSize(new java.awt.Dimension(400, 185));

        jRadioButton2.setText("Búsqueda Secuencial");
        jRadioButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRadioButton2ActionPerformed(evt);
            }
        });

        jRadioButton3.setText("Shell Sort");
        jRadioButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRadioButton3ActionPerformed(evt);
            }
        });

        jRadioButton1.setSelected(true);
        jRadioButton1.setText("Burbuja");
        jRadioButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRadioButton1ActionPerformed(evt);
            }
        });

        jRadioButton4.setText("Radix Sort");
        jRadioButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRadioButton4ActionPerformed(evt);
            }
        });

        jButton1.setText("Ordenar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
private void jRadioButton2ActionPerformed(java.awt.event.ActionEvent evt) {
        setOpc(2);
    }

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        switch (getOpc()) {
        case 1:
            System.out.println("\n\nBurbuja: ");
            metodos.Burbuja();
            metodos.mostrar();
            break;
        case 2:
            String n = JOptionPane.showInputDialog(null, "Numero a Buscar:");
            int num = Integer.parseInt(n);
            System.out.println("\nBusqueda Secuencial: ");
            metodos.busquedaSecuencial(num);
            break;
        case 3:
            System.out.println("\n\nShell Sort: ");
            metodos.shellSort();
            metodos.mostrar();
            break;
        case 4:
            System.out.println("\n\nRadix Sort: ");
            metodos.radixSort();
            metodos.mostrar();
            break;
        }
    }

    private void jRadioButton3ActionPerformed(java.awt.event.ActionEvent evt) {
        setOpc(3);
    }

    private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        setOpc(1);
    }

    private void jRadioButton4ActionPerformed(java.awt.event.ActionEvent evt) {
        setOpc(4);
    }

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
        switch (jList1.getSelectedIndex()) {
        case 0:
            System.out.print("\nVector Desordenado: \n");
            metodos.mostrar();
            break;
        case 1:
            String nInsert = JOptionPane.showInputDialog(null, "Numero a Insertar:");
            int nInsert2 = Integer.parseInt(nInsert);
            metodos.insertarNumero(nInsert2);
            break;
        case 2:
            String nInsert3 = JOptionPane.showInputDialog(null, "Numero a Eliminar:");
            int nInsert4 = Integer.parseInt(nInsert3);
            metodos.eliminarNumero(nInsert4);
            break;
        case 3:
            System.out.println("");
            System.exit(0);
        }
    }

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        /*
        * Set the Nimbus look and feel
        */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
        * If Nimbus (introduced in Java SE 6) is not available, stay with the
        * default look and feel. For details see
        * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
        */
        try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Ventana.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Ventana.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Ventana.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Ventana.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
        * Create and display the form
        */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new Ventana().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JList jList1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JRadioButton jRadioButton1;
    private javax.swing.JRadioButton jRadioButton2;
    private javax.swing.JRadioButton jRadioButton3;
    private javax.swing.JRadioButton jRadioButton4;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration
    /**
    * @return the opc
    */
    public int getOpc() {
        return opc;
    }

    /**
    * @param opc the opc to set
    */
    public void setOpc(int opc) {
        this.opc = opc;
    }
}
Clase MetodosOrdenamiento

/**
*
* @author Jesus Ivan
*/
public class MetodosOrdenamiento {
public int arrFijo[] = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 };
public int arr[] = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 };

public void restablecer() {
int tam = this.arr.length;
int newvector[] = new int[tam];
System.arraycopy(this.arrFijo, 0, newvector, 0, newvector.length);
this.arr = newvector;
}

public void insertarNumero(int num) {
int tam = this.arr.length;
int[] newvector = new int[tam+1];
System.arraycopy(this.arr, 0, newvector, 0, newvector.length-1);

this.arr = newvector;
this.arr[tam] = num;
this.arrFijo = newvector;
this.arrFijo[tam] = num;
}

public void eliminarNumero(int x) {
int nPosicion=0;
for (int j=0; j < arr.length; j++) {
if ( arr[j]== x ) {
nPosicion = j;
break;
} else {
if (j == arr.length)
System.out.println("Elemento no Encontrado");
}
}

for (int k = nPosicion; k < this.arr.length-1; k++)
this.arr[k] = this.arr[k+1];

int tam = this.arr.length;
int[] newvector = new int[tam-1];
for (int i = 0; i < newvector.length; i++)
newvector[i] = this.arr[i];

this.arr = newvector;
this.arrFijo = newvector;
}

public void Burbuja() {
int n = arr.length;
int aux;
int control = 0;

for (int j = n-1; j > 0; j--)
for (int i =0; i < j; i++)
if (arr[i] > arr[i+1]) {
aux = arr[i];
arr[i] = arr[i+1];
arr[i+1] = aux;
control = 0;
} else {
control++;
if (control == j)
j=0;
}
}

public void busquedaSecuencial(int x) {
for (int i=1; i <= arr.length; i++) {
if ( arr[i-1]== x ) {
System.out.println("Elemento Encontrado");
System.out.println("Posicion: " + (i-1));
break;
} else {
if (i == arr.length)
System.out.println("Elemento no Encontrado");
}
}
}


public void shellSort() {
int salto;
int cambios;
int aux;
int i;
for (salto=(arr.length/2); salto!=0; salto/=2) {
for (cambios=1; cambios!=0Wink {
cambios=0;
for (i=salto; i<arr.length; i++) {
if (arr[i-salto]>arr[i]) {
aux=arr[i];
arr[i]=arr[i-salto];
arr[i-salto]=aux;
cambios++;
}
}
}
}
}

public void radixSort() {
int tam = arr.length;
int[] control = new int[tam];
int[] siguiente = new int[tam];
int[] delante = new int[10];
int[] atras = new int[10];
int num=0, primero=0, i=0, j=0, k=0, p=0, q=0, y=0;

for (i=0; i<10; i++ ) {
control[i]=arr[i];
siguiente[i]=i+1;
}

control[tam-1]=arr[tam-1];
siguiente[tam-1]=-1;
primero=0;

for (k=1; k<4; k++) {
for (i=0; i<(tam-1); i++) {
atras[i]=-1;
delante[i]=-1;
}
while (primero!=-1) {
p=primero;
primero=siguiente[primero];
y=control[p];
num=1;

for (i=1; i<=k-1; i++)
num=num*10;

j=(y/num) % 10;
q=atras[j];
if (q==-1) {
delante[j]=p;
} else {
siguiente[q]=p;
}

atras[j]=p;
}
for (j=0; (j<10)&&(delante[j]==-1); j++);
primero=delante[j];
while (j<=9) {
for (i=j+1; (i<10)&&(delante[i]==-1); i++);
if (i<=9) {
p=i;
siguiente[atras[j]]=delante[i];
}
j=i;
}

if (atras[p]!=-1)
siguiente[atras[p]]=-1;
}

for (i=0; i<tam; i++) {
arr[i]=control[primero];
primero=siguiente[primero];
}
}

public void mostrar() {
for (int i =0; i < this.arr.length; i++)
System.out.print(this.arr[i] + ", ");
restablecer();
}
}


Vídeo



Descarga el código
Métodos de ordenamiento

Autor: Viruz study
Enlace: Métodos de ordenamiento en Java
Admin (Viruz)
Admin (Viruz)
Admin

Mensajes : 148
Fecha de inscripción : 23/09/2012
Edad : 35
Localización : Desktop

https://viruz.foroactivo.mx

Volver arriba Ir abajo

Volver arriba

- Temas similares

 
Permisos de este foro:
No puedes responder a temas en este foro.