Integrantes: Daniel Ivan Meza Lara Juan Francisco Posada ... · PDF filenúmero de...
Transcript of Integrantes: Daniel Ivan Meza Lara Juan Francisco Posada ... · PDF filenúmero de...
Integrantes:
Daniel Ivan Meza Lara
Juan Francisco Posada Romero
David Felipe Toca Avila
Cesar Alfredo Solinas Dueñas
Tema : Radix Sort
Bibliografia:
http://es.wikipedia.org/wiki/Ordenamiento_Radix
http://www-2.dc.uba.ar/materias/intcomp/teoricas/Clase3.pdf
http://www-2.dc.uba.ar/materias/intcomp/teoricas/Clase2.pdf
Historia
En EE.UU en 1880 no se puede terminar el censo de la década anterior (en concreto, no se llega a contar el
número de habitantes solteros)
Herman Hollerith (empleado de la oficina del censo, de 20 años de edad) inventa una máquina tabuladora
eléctrica para resolver el problema; en esencia es una implementación física del radix sort 1890: se usan
unas 100 máquinas de Hollerith para tabular las listas del censo de la década (un operador experto
procesaba 19.071 tarjetas en una jornada laboral de 6’5 horas, unas 49 tarjetas por minuto)
1896: Hollerith crea la empresa Tabulating Machine Company 1900: Hollerith resuelve otra crisis federal
inventando una nueva máquina con alimentación automática de tarjetas (útil, con más o menos variaciones,
hasta 1960)
1911: la empresa de Hollerith se fusiona con otras dos, creando la Calculating-Tabulating- Recording
Company (CTR)
1924: Thomas Watson cambia el nombre a la CTR y la llama
International Business Machines (IBM) El resto de la historia es conocida.
Analisis del algoritmo
Se trata de hacer diversos montones de fichas, cada uno caracterizado por tener en sus componentes un mismo digito (letra si es alfabética) en la misma posición; estos montones se recogen en orden ascendente y se reparte en montones según el siguiente digito de la clave para llegar a un ordenamiento
Definicion del problema
ordenar un lista de numeros de menorr a mayor
Especificacion de entrada
C , N
Por consola
Espeificacion de salida
El arreglo ordenado
Imprime el ordenamiento en la pantalla
Complejidad
O(d*n) = O(n)
Tiempo total de ejecucion
O(d ・ n + 10 ・ d).
Mejor caso
Peorcaso
Caso promedio
Estabilidad
Memoria adicional
comparacion
Complejidad
Tiempo total de ejecucion
RadixSort
O(n)
O(n)
O(n)
Estable
Si
No compara
O(d*n) =O(n)
O(d・n+10・d).
codigo java.
import java.awt.*;
import java.applet.Applet;
import java.util.*;
import java.awt.event.*;
import java.lang.*;
public class OtroNivelEnRadixSort extends Applet implements
ActionListener {
Choice chDigit;
Choice chRetardo;
Choice chElementos;
java.awt.List codigo;
CArreglo cRadix;
Button btnOrdenar;
Vector arreglo;
Label orden;
Label lIteraciones;
Label antes;
Label despues;
int iteraciones;
// int retardo;
int cuenta[];
/**
* Initialization method that will be called after the applet is
loaded into
* the browser.
*/
public void init() {
cuenta = new int[10];
setSize(1050, 490);
crearInterfaz();
}
private String getArreglo(Vector vec) {
StringBuilder sb = new StringBuilder();
sb.append("[ ");
for (Object a : vec) {
sb.append(((String) a).substring(1) + " ");
}
sb.append("]");
return new String(sb);
}
public void paint(Graphics g) {
cRadix.repinta();
}
public void update(Graphics g) {
paint(g);
}
public void crearInterfaz() {
setLayout(new BorderLayout());
arreglo = new Vector();
Panel pTop = new Panel();
Panel pWest = new Panel(new GridLayout(1, 1));
Panel pCenter = new Panel();
Panel pSout = new Panel(new GridLayout(3, 1));
Panel pDigit = new Panel();
// Panel pRetardo = new Panel();
Panel pElementos = new Panel();
Panel pOrdenar = new Panel();
Panel pOrden = new Panel(new GridLayout(1, 1));
Panel pan1 = new Panel(new GridLayout(1, 1));
cRadix = new CArreglo();
cRadix.setSize(455, 400);
cRadix.setBackground(Color.black);
pCenter.add(cRadix);
codigo = new java.awt.List();
codigo.setSize(100, 300);
mostrarCodigo();
pWest.add(codigo);
btnOrdenar = new Button("Ordenar...");
btnOrdenar.addActionListener(this);
pOrdenar.add(btnOrdenar);
chDigit = new Choice();
for (int i = 1; i <= 5; i++)
chDigit.add(Integer.toString(i));
pDigit.add(new Label("Dígitos: "));
pDigit.add(chDigit);
chDigit.select(0);
chRetardo = new Choice();
for (int i = 1; i <= 10; i++)
chRetardo.add(Integer.toString(i * 100));
// pRetardo.add(new Label("Retardo: "));
// pRetardo.add(chRetardo);
chRetardo.select(0);
chElementos = new Choice();
for (int i = 2; i <= 100; i++)
chElementos.add(Integer.toString(i));
pElementos.add(new Label("Elementos: "));
pElementos.add(chElementos);
chElementos.select(0);
orden = new Label("Orden O( n )");
// orden.set
lIteraciones = new Label("Iteraciones = 0");
pOrden.add(orden);
pOrden.add(lIteraciones);
antes = new Label("Arreglo Inicial: ");
// antes.
// pOrden.add(antes);
// despues=new Label("Arreglo Final: ");
// pOrden.add(despues);
Panel pOpciones = new Panel();
pOpciones.add(pDigit);
pOpciones.add(pElementos);
// pOpciones.add(pRetardo);
pOpciones.add(pOrdenar);
pSout.add(pOrden);
pSout.add(pOpciones);
pan1.add(antes);
pSout.add(pan1);
add(pWest, BorderLayout.WEST);
add(pCenter, BorderLayout.CENTER);
add(pSout, BorderLayout.SOUTH);
}
public void mostrarCodigo() {
codigo.removeAll();
codigo.add("____________________________");
codigo.add("");
codigo.add("RadixSort( A[ ], n, d");
codigo.add(" for (int i= 1; i <= d; i--)");
codigo.add(" A = CountingSort(A, n, 10, i)");
codigo.add("Fin RadixSort");
codigo.add("");
codigo.add("____________________________");
codigo.add("____________________________");
codigo.add("");
codigo.add("CountingSort( A[ ], n, k, digit )");
codigo.add(" C[ ] = 0");
codigo.add(" for ( j = 1; j <= n; j++)");
codigo.add(" C[ A[ j ][digit] ] ++");
codigo.add(" for ( i = 2; j <= k; j++)");
codigo.add(" C[ i ] += C[ i - 1 ]");
codigo.add(" for ( j = n; j >= 1; j--)");
codigo.add(" e = A[ j ][digit]");
codigo.add(" B[ C[ e ] ] = A[ j ]");
codigo.add(" C[ e ]--");
codigo.add(" return B");
codigo.add("Fin CountingSort");
codigo.add("");
codigo.add("____________________________");
}
public Vector radixSort(Vector A, int n, int d) {
codigo.select(3);
// esperar(retardo);
for (int i = d; i > 0; i--) {
codigo.select(4);
cRadix.imprimeMsg("Dígito " + Integer.toString(d - i + 1)
+ ".- Contando");
// esperar(retardo);
A = countingSort(A, n, d, i);
codigo.select(3);
// esperar(retardo);
}
for (int i = 0; i < n; i++) {
A.setElementAt(
Integer.toString(0)
+ ((String) A.elementAt(i)).substring(1), i);
}
codigo.select(5);
cRadix.dibujaArreglo(A, n, d);
cRadix.imprimeMsg("Arreglo ordenado");
return A;
}
public void generaArreglo(int n, int d) {
String elem;
int t;
arreglo.removeAllElements();
for (int i = 0; i < n; i++) {
elem = new String(Integer.toString(d + 1));
for (int j = 0; j < d; j++) {
t = (int) (Math.random() * 10);
elem = elem + Integer.toString(t);
}
arreglo.addElement(elem);
}
}
public Vector countingSort(Vector A, int n, int d, int e) {
char ind[] = new char[1];
int pos;
Vector B = new Vector();
codigo.select(10);
// esperar(retardo);
codigo.select(11);
// esperar(retardo);
for (int i = 0; i < n; i++)
B.addElement(new String(""));
for (int i = 0; i < 10; i++)
cuenta[i] = 0;
codigo.select(12);
// esperar(retardo/4);
for (int i = 0; i < n; i++) {
codigo.select(13);
// esperar(retardo/2);
ind[0] = ((String) A.elementAt(i)).charAt(e);
cuenta[Integer.parseInt(new String(ind))] += 1;
cRadix.dibujaNum(i, e, A);
cRadix.dibujaCuenta(cuenta);
codigo.select(12);
// esperar(retardo/2);
}
codigo.select(14);
// esperar(retardo/4);
for (int i = 1; i < 10; i++) {
codigo.select(15);
// esperar(retardo/2);
cRadix.imprimeMsg("Digito " + Integer.toString(d - e + 1)
+ ".- Contando números <= " + Integer.toString(i));
cuenta[i] += cuenta[i - 1];
cRadix.dibujaCuenta(cuenta);
codigo.select(14);
// esperar(retardo/2);
}
cRadix.imprimeMsg("Digito " + Integer.toString(d - e + 1)
+ ".- Ordenando");
codigo.select(16);
// esperar(retardo/4);
for (int i = n - 1; i >= 0; i--) {
codigo.select(17);
// esperar(retardo/4);
ind[0] = ((String) A.elementAt(i)).charAt(e);
pos = Integer.parseInt(new String(ind));
codigo.select(18);
// esperar(retardo/4);
B.setElementAt(
Integer.toString(e)
+ ((String) A.elementAt(i)).substring(1),
cuenta[pos] - 1);
codigo.select(19);
lIteraciones.setText("Iteraciones = "
+ Integer.toString(++iteraciones));
// esperar(retardo/4);
--cuenta[pos];
cRadix.dibujaCuenta(cuenta);
cRadix.dibujaArreglo(B, n, d);
codigo.select(16);
// esperar(retardo/4);
}
codigo.select(20);
// esperar(retardo/2);
return B;
}
// public void esperar(long milisec) {
// try {
// Thread.sleep(milisec);
// } catch (InterruptedException e) {
// }
// }
public void actionPerformed(ActionEvent e) {
int d, n;
d = n = 0;
if (e.getSource() == btnOrdenar) {
long tiempoInicio = System.currentTimeMillis();
try {
n = Integer.parseInt(chElementos.getSelectedItem());
d = Integer.parseInt(chDigit.getSelectedItem());
// retardo =
Integer.parseInt(chRetardo.getSelectedItem());
} catch (NumberFormatException ex) {
}
cRadix.imprimeMsg("Generando Arreglo");
// esperar(retardo);
iteraciones = 0;
generaArreglo(n, d);
orden.setText("Para c = " + Integer.toString(d) + " y n = "
+ Integer.toString(n) + ", O(n) = c(n) = "
+ Integer.toString(n * d));
// orden.setText(orden.getText()+"\t\n"+getArreglo(arreglo));
antes.setText("Arreglo Inicial: " + getArreglo(arreglo));
System.out.println(antes.getText());
// orden.setText(orden.getText()+"\n"+)
lIteraciones.setText("Iteraciones = "
+ Integer.toString(iteraciones));
cRadix.dibujaArreglo(arreglo, n, d);
cRadix.imprimeMsg("Arreglo Generado");
for (int i = 0; i < 10; i++)
cuenta[i] = 0;
cRadix.dibujaCuenta(cuenta);
cRadix.imprimeMsg("Ordenando Arreglo");
codigo.select(2);
// esperar(retardo);
// despues.setText("Arreglo Final:
"+getArreglo(radixSort(arreglo,
// n, d)));
System.out.println("Arreglo Final: "
+ getArreglo(radixSort(arreglo, n, d)));
long totalTiempo = System.currentTimeMillis() - tiempoInicio;
cRadix.imprimeMsg("Arreglo Ordenado. Tiempo: " +
totalTiempo+ " Milisegundos");
}
}
protected class CArreglo extends Canvas {
Image img = null;
public void dibujaNum(int i, int j, Vector A) {
Graphics gr;
int x1, x, y, y1;
char str[];
str = new char[1];
Color ct = Color.black;
gr = img.getGraphics();
x1 = 5;
x = x1 + j * 15;
y = (15 * (i + 1));
if ((i >= 20) && (i < 40)) {
i -= 20;
x1 += 90;
} else if ((i >= 40) && (i < 60)) {
i -= 40;
x1 += 180;
} else if ((i >= 60) && (i < 80)) {
i -= 60;
x1 += 270;
} else if ((i >= 80) && (i < 100)) {
i -= 80;
x1 += 360;
} else
x1 = 5;
x = x1 + j * 15;
y = (15 * (i + 1));
str[0] = ((String) A.elementAt(i)).charAt(j);
Color cf = colorF(Integer.parseInt(new String(str)));
gr.setColor(cf);
gr.fill3DRect(x, y, 14, 14, true);
gr.setColor(ct);
gr.drawString(new String(str), x + 2, y + 12);
this.getGraphics().drawImage(img, 0, 0, null);
this.update(this.getGraphics());
}
public void dibujaArreglo(Vector A, int n, int d) {
Graphics gr;
int x, y;
char str[];
Color cf, ct;
cf = Color.red;
ct = Color.white;
if (img == null)
img = createImage(getSize().width, getSize().height);
gr = img.getGraphics();
gr.clearRect(0, 0, this.getSize().width, 316);
x = 2;
y = 2;
gr.setColor(Color.white);
for (int i = 1; i <= 20; i++) {
gr.drawString(Integer.toString(i), 2, 15 + i * 15);
}
for (int i = 1; i < n; i += 20) {
gr.drawString(Integer.toString(i), (i / 20) * 90 + 45,
13);
}
x = 20;
y = 15;
for (int i = 0; i < n; i++) {
if (y == 315) {
y = 15;
x += 90;
}
int c;
d = ((String) A.elementAt(i)).length() - 1;
str = new char[1];
for (int j = d; j >= 1; j--) {
str[0] = ((String) A.elementAt(i)).charAt(0);
c = Integer.parseInt(new String(str));
str[0] = ((String) A.elementAt(i)).charAt(j);
if (c == j) {
gr.setColor(Color.white);
gr.draw3DRect(x + (j - 1) * 15 - 1, y - 1, 15,
15, true);
cf = colorF(Integer.parseInt(new String(str)));
ct = Color.black; // colorT(Integer.parseInt(new
// String(str)));
} else {
gr.setColor(Color.gray);
gr.draw3DRect(x + (j - 1) * 15 - 1, y - 1, 15,
15, true);
if ((c == 0) || (j >= c)) {
cf = Color.gray;
ct = colorF(Integer.parseInt(new
String(str)));
} else {
cf = Color.black;
ct = Color.lightGray;
// ct = colorF(Integer.parseInt(new
String(str)));
}
}
gr.setColor(cf);
gr.fill3DRect(x + (j - 1) * 15, y, 14, 14, true);
gr.setColor(ct);
gr.drawString(new String(str), x + (j - 1) * 15 + 2,
y + 12);
}
y += 15;
}
this.getGraphics().drawImage(img, 0, 0, null);
this.update(this.getGraphics());
}
protected void dibujaCuenta(int cuenta[]) {
Graphics gr;
int x, y;
Font f1, f2;
x = 70;
y = 370;
Color cf, ct;
if (img == null)
img = createImage(getSize().width, getSize().height);
gr = img.getGraphics();
gr.clearRect(0, y - 20, this.getSize().width, 40);
f1 = gr.getFont();
f2 = new Font("Lucida Sans", Font.BOLD, 16);
cf = Color.red;
ct = Color.red;
gr.setColor(cf);
gr.setFont(f2);
gr.drawString("C[ ] =", 15, y + 15);
gr.setFont(f1);
for (int i = 0; i < cuenta.length; i++) {
cf = colorF(i);
ct = Color.black; // colorT(i);
gr.setColor(cf);
gr.fill3DRect(x + i * 30 + 1, y, 30, 20, true);
gr.drawString(Integer.toString(i), x + i * 30 + 11, y -
2);
gr.setColor(ct);
gr.drawString(Integer.toString(cuenta[i]), x + i * 30 +
6,
y + 17);
}
this.getGraphics().drawImage(img, 0, 0, null);
this.update(this.getGraphics());
}
protected Color colorF(int d) {
switch (d) {
case 0:
return Color.white;
case 1:
return Color.yellow;
case 2:
return Color.red;
case 3:
return Color.pink;
case 4:
return new Color(148, 190, 176);
case 5:
return Color.magenta;
case 6:
return new Color(197, 186, 124);
case 7:
return Color.green;
case 8:
return Color.cyan;
}
return new Color(250, 175, 107);
}
protected Color colorT(int d) {
switch (d) {
case 0:
return Color.black;
case 1:
return Color.black;
case 2:
return Color.black;
case 3:
return Color.black;
case 4:
return Color.black;
case 5:
return Color.black;
case 6:
return Color.black;
case 7:
return Color.black;
case 8:
return Color.black;
}
return Color.black;
}
protected void imprimeMsg(String msg) {
Graphics gr;
Font f, temp;
int x, y;
f = new Font("Lucida Sans", Font.BOLD, 16);
x = 70;
y = 325;
if (img == null)
img = createImage(getSize().width, getSize().height);
gr = img.getGraphics();
gr.clearRect(0, y, this.getSize().width, 20);
temp = gr.getFont();
gr.setColor(Color.lightGray);
gr.setFont(f);
gr.drawString(msg, x, y + 15);
gr.setFont(temp);
this.getGraphics().drawImage(img, 0, 0, null);
this.update(this.getGraphics());
}
protected Color color(int c) {
switch (c) {
case 1:
return new Color(96, 159, 139);
case 2:
return Color.yellow;
case 3:
return Color.cyan;
case 4:
return Color.lightGray;
}
return Color.white;
}
public void repinta() {
this.update(this.getGraphics());
}
public void update(Graphics g) {
this.paint(g);
}
public void paint(Graphics g) {
if (img != null)
g.drawImage(img, 0, 0, null);
}
}
}