INSTITUTO DE INVESTIGACIÓN
2007
iii
Estructura de Datos con Java
v
Estructura de Datos con Java
Mg. Abraham Esteban Gamarra Moreno
Mg. Job Daniel Gamarra Moreno
Tiraje: 20 ejemplares
Explicación de la portada.
La portada muestra la relación que establece el uso de las Estructuras de Datos con la re-
presentación de bajo nivel de la información.
Derechos Reservados.
Prohibida la reproducción total o parcial por cualquier medio sin permiso de los autores.
Libro Electrónico editado en la Universidad Nacional del Centro del Perú, en Huan-
cayo, Perú.
Diagramación:
Mg. Abraham Esteban Gamarra Moreno
Mg. Job Daniel Gamarra Moreno
CONTENIDO ........................................................................................................................................IX
INTRODUCCION............................................................................................................................... XV
RECURSION .........................................................................................................................................67
4.1. ALGORITMOS RECURSIVOS ....................................................................................................67
4.2. PROBLEMAS PROPUESTOS ......................................................................................................72
CAPITULO CINCO..............................................................................................................................75
PILAS Y COLAS...................................................................................................................................75
5.1. PILAS (LIFO) ........................................................................................................................75
5.1.1. Operaciones básicas ........................................................................................................76
5.1.2. Implementación de pilas con referencias.........................................................................76
5.2. COLAS (FIFO) .......................................................................................................................78
5.2.1. Operaciones.....................................................................................................................78
5.2.2. Implementación de colas con referencias........................................................................79
5.3. PROGRAMAS EJEMPLO ...........................................................................................................81
CAPITULO SEIS ..................................................................................................................................97
ARBOLES ..............................................................................................................................................97
6.1. ÁRBOLES EN GENERAL ..........................................................................................................97
6.2. CARACTERÍSTICAS Y PROPIEDADES DE LOS ÁRBOLES ............................................................98
6.3. ARBOL BINARIO...................................................................................................................100
6.3.1. Definiciones ...................................................................................................................101
6.4. REPRESENTACIÓN DE ÁRBOLES GENERALES COMO BINARIOS ..............................................102
6.5. RECORRIDO DE UN ÁRBOL ...................................................................................................103
6.5.1. Recorrido en Preorden ..................................................................................................104
6.5.2. Recorrido en Inorden.....................................................................................................104
6.5.3. Recorrido en Postorden .................................................................................................104
6.6. IMPLEMENTACIÓN DE UN ÁRBOL MEDIANTE REFERENCIAS ..................................................106
6.6.1. Implementación del recorrido PreOrden.......................................................................107
6.6.2. Implementación del recorrido InOrden .........................................................................108
6.6.3. Implementación del recorrido PostOrden .....................................................................109
6.7. ÁRBOL BINARIO DE BÚSQUEDA ...........................................................................................110
6.7.1. Inserción en un arbol binario de búsqueda ...................................................................111
6.7.2. Borrado en un arbol binario de búsqueda.....................................................................114
6.8. CLASE GENERICA PARA LA IMPLEMENTACIÓN DE ARBOLES CON REFERENCIAS ...................117
CAPITULO SIETE .............................................................................................................................123
OBJETOS Y CLASES
Abrir el flujo
Abrir el flujo
Mientras haya más información
Mientras haya más información
leer la información
escribir información
cerrar el flujo
cerrar el flujo
Flujo sumidero de
datos
Flujo de procesa-
miento
Variable = System.in.read()
System.out.write(parametro)
//archivo: lecturabytes.java
import java.io.*;
class lecturabytes
{
public static void main (String[] args)
throws IOException
{
// declaración de las variables
int n;
//lee un byte
n=System.in.read();
//escribe un byte
System.out.write(n);
//escribe un salto de línea
System.out.write('\n');
}
}
InputStream Reader
OutputStream Writer
caracteres bytes
Figura 1.3
import java.io.*;
class lecturacadenas
{
public static void main (String[] args)
throws IOException
{
// Definir un flujo de caracteres de entrada:
flujoE
Class Integer
Constructores
Integer(int value)
Construye un objeto Integer que representa el
valor especifico del int.
Integer(String s)
Construye un objeto Integer que representa el
valor int indicado por el parámetro String.
1
Fuente: JDK HELP
Mg. Daniel Gamarra Moreno - Mg. Abraham Gamarra Moreno 13
boolean equals(Object obj)
Compares this object to the speci-
fied object.
float floatValue()
Returns the value of this Integer as
a float.
static Integer getInteger(String nm)
Determines the integer value of the
system property with the specified name.
static Integer getInteger(String nm, int val)
Determines the integer value of the
system property with the specified name.
static Integer getInteger(String nm, Integer val)
Returns the integer value of the
system property with the specified name.
int hashCode()
Returns a hash code for this Inte-
ger.
int intValue()
Returns the value of this Integer as
an int.
long longValue()
Returns the value of this Integer as
a long.
static int parseInt(String s)
Parses the string argument as a
signed decimal integer.
static int parseInt(String s, int radix)
Parses the string argument as a
signed integer in the radix specified by the
second argument.
short shortValue()
Returns the value of this Integer as
a short.
static String toBinaryString(int i)
Returns a string representation of
the integer argument as an unsigned integer
in base 2.
static String toHexString(int i)
Returns a string representation of
the integer argument as an unsigned integer
in base 16.
Class Float
2
Fuente: HELP JDK 2 Ver 1.4 (Idioma Original)
Mg. Daniel Gamarra Moreno - Mg. Abraham Gamarra Moreno 15
tive nonzero value of type float.
static float NaN
A constant holding a Not-a-Number
(NaN) value of type float.
static float NEGATIVE_INFINITY
A constant holding the negative in-
finity of type float.
static float POSITIVE_INFINITY
A constant holding the positive in-
finity of type float.
static Class TYPE
The Class instance representing the
primitive type float.
Constructores
Float(double value)
Constructs a newly allocated Float object that
represents the argument converted to type float.
Float(float value)
Constructs a newly allocated Float object that
represents the primitive float argument.
Float(String s)
Constructs a newly allocated Float object that
represents the floating-point value of type float repre-
sented by the string.
Métodos
byte byteValue()
Returns the value of this Float as a
byte (by casting to a byte).
static int compare(float f1, float f2)
Compares the two specified float
values.
int compareTo(Float anotherFloat)
Compares two Float objects numeri-
cally.
int compareTo(Object o)
Compares this Float object to an-
other object.
double doubleValue()
16 Mg. Daniel Gamarra Moreno - Mg. Abraham Gamarra Moreno
Returns the double value of this
Float object.
boolean equals(Object obj)
Compares this object against the
specified object.
static int floatToIntBits(float value)
Returns a representation of the
specified floating-point value according to
the IEEE 754 floating-point "single format"
bit layout.
static int floatToRawIntBits(float value)
Returns a representation of the
specified floating-point value according to
the IEEE 754 floating-point "single format"
bit layout, preserving Not-a-Number (NaN)
values.
float floatValue()
Returns the float value of this Float
object.
int hashCode()
Returns a hash code for this Float
object.
static float intBitsToFloat(int bits)
Returns the float value correspond-
ing to a given bit represention.
int intValue()
Returns the value of this Float as
an int (by casting to type int).
boolean isInfinite()
Returns true if this Float value is
infinitely large in magnitude, false other-
wise.
static boolean isInfinite(float v)
Returns true if the specified number
is infinitely large in magnitude, false other-
wise.
boolean isNaN()
Returns true if this Float value is a
Not-a-Number (NaN), false otherwise.
static boolean isNaN(float v)
Returns true if the specified number
is a Not-a-Number (NaN) value, false other-
wise.
long longValue()
import java.io.*;
//import java.lang.*;
class lecturanumeros
{
public static void main (String[] args)
throws IOException
{
// Definir un flujo de caracteres de entrada: flujoE
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader flujoE = new BufferedReader(isr);
nume=Integer.parseInt(sdato);//convierte cadena a
// entero
nume=nume+5;
System.out.println("el numero + 5 es : "+nume);
numf=Float.parseFloat(sdato);//convierte cadena a
//float
numf=numf+5;
System.out.println("el numero + 5 es : "+numf);
}
}
import java.io.*;
class operarit
{
public static void main (String[] args)
throws IOException
{
// Definir un flujo de caracteres de entrada: flujoE
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader flujoE = new BufferedReader(isr);
/**
* Valor a almacenar
* @param x numero a almacenar
*/
public void write( int x ){
storedValue = x;
}
1.5.1. CONSTRUCTORES
// Archivo: Cuenta.java
import java.lang.Math;
class Cuenta
{ private float saldo;
import java.io.*;
class CuentaAppl
{
public static void main (String[] args)
throws IOException
{
// Definir un flujo de caracteres de entrada: flujoE
InputStreamReader isr = new
InputStreamReader(System.in);
BufferedReader flujoE = new BufferedReader(isr);
//lectura de datos
System.out.print("Introduzca saldo inicial: ");
sdato = flujoE.readLine(); // leer una línea de texto
sal=Float.parseFloat(sdato);//convierte cadena a float
c.asignar(sal);
c.escribir();
c.deposito(dep);
c.escribir();
c.retiro(ret);
c.escribir();
}
28 Mg. Daniel Gamarra Moreno - Mg. Abraham Gamarra Moreno
}
// Archivo: Cuenta1.java
import java.io.*;
class Cuenta1
{ private float saldo;
// Archivo Cuenta1Appl.java
import java.io.*;
class Cuenta1Appl
{
public static void main (String[] args)
throws IOException
{
//Creación de un objeto Cuenta1
Cuenta1 c=new Cuenta1();
c.asignar();
c.escribir();
c.deposito();
c.escribir();
c.retiro();
c.escribir();
}
}
// Archivo: Cuenta2.java
import java.io.*;
class Cuenta2
{ private float saldo;
// Archivo Cuenta2Appl.java
import java.io.*;
class Cuenta2Appl
{
public static void main (String[] args)
{
//Creación de un objeto Cuenta2: c
Cuenta2 c=new Cuenta2();
c.asignar();
c.escribir();
c.deposito();
c.escribir();
// Archivo: Complejo.java
import java.lang.Math;
class Complejo
{ private float real;
private float imaginario;
Complejo()
{ real=0;
imaginario=0;
}
// Archivo ComplejoAppl.java
class ComplejoAppl
{
public static void main (String[] args)
throws IOException
{
// Definir un flujo de caracteres de entrada: flujoE
InputStreamReader isr = new
InputStreamReader(System.in);
BufferedReader flujoE = new BufferedReader(isr);
//lectura de datos
System.out.print("Introduzca parte real: ");
sdato = flujoE.readLine(); // leer una línea de texto
re=Float.parseFloat(sdato);//convierte cadena a float
System.out.print("Introduzca parte imaginaria: ");
sdato = flujoE.readLine(); // leer una línea de texto
im=Float.parseFloat(sdato);//convierte cadena a float
}
}
Un modelo matemático y
EJEMPLO UNO
Ningún computador puede almacenar exactamente al
número racional 1/3, por ejemplo. Sin embargo puede
ser necesario operar sólo en aritmética racional.
p
( p, q ) para , q≠0
q
Operaciones:
Multiplicación de racionales
(p , q) . (p’ , q’) = (p p’ , q q’)
CRacional(){
rational[0]=0;
rational[1]=0;
}
for (i=0;i<max;i++){
System.out.print("ingrese elemento "+(i+1)+":");
rational[i]=Leer.datoInt();
}
}
su.rational[0]=rational[0]*y.rational[1]+rational[1]*y.rational[0];
su.rational[1]=rational[1]*y.rational[1];
su.simplificar();
return su;
}
mu.rational[0]=rational[0]*y.rational[0];
mu.rational[1]=rational[1]*y.rational[1];
mu.simplificar();
return mu;
}
a=rational[0];
b=rational[1];
while(b!=0){
res=a % b;
a=b;
b=res;
}
rational[0]/=a;
rational[1]/=a;
}
CRacional(){
num=0;
den=0;
}
su.num=num*y.den+den*y.num;
su.den=den*y.den;
su.simplificar();
return su;
}
mu.num=num*y.num;
mu.den=den*y.den;
mu.simplificar();
38 Mg. Daniel Gamarra Moreno - Mg. Abraham Gamarra Moreno
return mu;
}
a=num;
b=den;
while(b!=0){
res=a % b;
a=b;
b=res;
}
num/=a;
den/=a;
}
}
EJEMPLO DOS
Se tiene un TDA enterazo que guarda un numero ente-
ro, cada cifra es un elemento de un arreglo de en-
teros. Se pide desarrollar un programa para las
operaciones suma y resta.
// La clase Leer debe estar en alguna carpeta de las especificadas
// por la variable de entorno CLASSPATH.
public class CEnterazo{
static int max=4;
int[] enterazo=new int[max];
CEnterazo(){
for(int i=0;i<max;i++) enterazo[i]=0;
}
x="";
for(i=0;i<max;i++) x=x+enterazo[i];
return x;
}
//halla la resta de dos enteros si el primero
//es mayor que el segundo
for(i=max-1;i>=0;i--)
if (enterazo[i]>=y.enterazo[i])
re.enterazo[i]=enterazo[i]-y.enterazo[i];
else{
re.enterazo[i]=(enterazo[i]+10)-y.enterazo[i];
y.enterazo[i-1]=y.enterazo[i-1]+1;
}//fin de else (x[i]>y[i])
return re;
}
for(i=max-1;i>=0;i--){
su.enterazo[i]=enterazo[i]+y.enterazo[i]+a;
if (su.enterazo[i]>=10){
a=su.enterazo[i]/10;//calcula acarreo
su.enterazo[i]=su.enterazo[i]%10;//halla lo que se queda
}
else a=0;
}
return su;
}
}
n1.leer_numero();
System.out.println("El primer numero es :"+n1);
n2.leer_numero();
System.out.println("El segundo numero es :"+n2);
r=n1.suma(n2);
System.out.println("La suma es :"+r);
r=n1.resta(n2);
System.out.println("La resta es :"+r);
}
}
x="";
for(i=0;i<max;i++) x=x+binario[i];
return x;
}
return x;
}
}
ESTRUCTURA DE DATOS EN JAVA 41
//archivo: CBinarioApp.java
// La clase Leer debe estar en alguna carpeta de las especificadas
// por la variable de entorno CLASSPATH.
public class CBinarioApp{
n1.leer_numero();
System.out.println("El numero es :"+n1);
EJEMPLO CUATRO
Implementación de la operación diferencia de un TDA
conjunto de 5 elementos enteros cada conjunto. El
conjunto se representa por un arreglo de enteros,
el conjunto diferencia si tiene menos de 5 elemen-
tos es completada con ceros.
// La clase Leer debe estar en alguna carpeta de las especificadas
// por la variable de entorno CLASSPATH.
CConjunto(){
for(int i=0;i<N;i++) Conjunto[i]=0;
}
Conjunto[0]=a;
Conjunto[1]=b;
Conjunto[2]=c;
Conjunto[3]=d;
Conjunto[4]=e;
}
for(i=0;i<N;i++){
v=Conjunto[i];//toma elemento de a para buscar en b
if(b.busca(v)==-1)//no existe elemento en b
{
d.Conjunto[j]=Conjunto[i];
j++;
}
}
//agrega los ceros a d
for(i=j;i<N;i++) d.Conjunto[i]=0;
return d;
}
x="";
for(i=0;i<N;i++)
if (Conjunto[i]!=0) x=x+Conjunto[i]+" ";
return x;
}
}
PROBLEMA UNO
PROBLEMA DOS
Escriba un programa que permita operar con números
complejos definido en su forma polar, en donde:
⎛b⎞
a + bi = r (cosθ + isenθ ) r = a2 + b2 θ = arctan⎜ ⎟
⎝a⎠
Operaciones
Suma:
Producto:
División:
r1 (cosθ 1 + i sen θ 1 ) r1
= (cos(θ 1 − θ 2 ) + i sen(θ 1 − θ ) )
r2 (cosθ 2 + i sen θ 2 ) r2
θ + 2kπ θ + 2kπ
n r (cosθ + i sen θ ) = n r (cos( ) + i sen( ))
n n
k = 0,1,2,..., n − 1
π = 3.1416
LISTAS ENLAZADAS
3.1.1. DEFINICIONES:
d) a1 es el primer elemento de L y an es
el último elemento de L.
L Nulo
Donde la clase de un nodo es:
Información
Tipo de datos que Una referencia que se utiliza para estable-
se quiere almacenar cer el enlace con el otro nodo de la lista.
en la lista.
ListaSimple(){
top=sig=null;
}
comienzo=top;
// Crear nuevo dato
nuevo=new ListaSimple();
p=new ListaSimple();
nuevo.info=x;
// Primer dato
if (comienzo==null){
comienzo=nuevo;
nuevo.sig=null;
}
else //valor antes de comienzo
if (x<comienzo.info){
nuevo.sig=comienzo;
comienzo=nuevo;
}
else {
// Nuevo se halla entre p y q luego
// de enlazarlos
q=comienzo;
while (q!=null && (x>=q.info)){
p=q;
q=q.sig;
}
p.sig=nuevo;
nuevo.sig=q;
}
top=comienzo;
}
System.out.println("Impresion de la lista");
p=top;
while(p!=null){
System.out.print("\t"+p.info);
p=p.sig;
}
System.out.println();;
}
p=new ListaSimple();
q=top;
if (q==null)
System.out.println("Lista vacia");
else{
while (q!=null && val!=q.info){
p=q;
q=q.sig;
}
if (q==null)
System.out.println("valor no encontrado");
else
if (q==primero())
top=top.sig;
else
p.sig=q.sig;
}
}
encontrado=false;
p=top;
while(p!=null && !encontrado)
if (x==p.info)
encontrado=true;
else
p=p.sig;
if (encontrado)
return p;
else
return null;
}
}
sw=1;
do{
System.out.println("\n\n\n\nProcesamiento de una Lista “+”
simplemente enlazada\n");
System.out.println("0. Salir");
System.out.println("1. Anula lista");
System.out.println("2. Suprime el elemento para un valor dado");
System.out.println("3. Inserta un elemento a la lista");
System.out.println("4. Contenido de la lista");
System.out.println("5. Localiza un elemento en la lista");
System.out.print("Opcion ==> ");
opcion=Leer.datoInt();
switch(opcion){
case 0:sw=0;break;
case 1:L.anula();break;
case 2:
System.out.print("Digite valor a suprimir ==> ");
x=Leer.datoInt();
L.suprime(x);
break;
case 3:
System.out.print("Digite valor a insertar ==> ");
x=Leer.datoInt();
L.inserta(x);
break;
case 4:
L.contenido();break;
case 5:
System.out.print("Digite valor a localizar ==> ");
x=Leer.datoInt();
p=L.localiza(x);
if (p==null)
System.out.println("No existe valor");
else
System.out.println("El valor encontrado es "+
p.info);
break;
}
}while(sw==1);
}
}
System.out.println("Impresion de la lista");
p=top;
if(p!=null){
while (p!=null){
System.out.print(""+p.info+"\t");
p=p.sig;
}
}
System.out.println();
}
System.out.println("Impresión de la lista");
p=bottom;
if(p!=null){
while (p!=null){
System.out.print(""+p.info+"\t");
p=p.ant;
}
}
System.out.println();
}
}
sw=1;
do{
System.out.println("\n\n\n\nProcesamiento de una lista
doblemente enlazada\n");
System.out.println("0. Salir");
System.out.println("1. Anula lista");
System.out.println("2. Inserta un elemento a la lista");
System.out.println("3. Contenido de la lista: Avance");
System.out.println("4. Contenido de la lista: Retrocede");
System.out.print("Opcion ==> ");
opcion=Leer.datoInt();
switch(opcion){
case 0:sw=0;break;
case 1:L.anula();break;
case 2:
System.out.print("Digite valor a insertar ==> ");
x=Leer.datoInt();
L.inserta(x);
break;
case 3:
L.ContenidoAvanza();break;
case 4:
L.ContenidoRetrocede();break;
}
}while(sw==1);
}
}
ListaSimpleCirc(){
top=sig=null;
}
System.out.println("Impresion de la lista");
p=top;
if(p!=null){
while(top!=p.sig){
System.out.print(""+p.info+"\t");
p=p.sig;
}
//p=p.sig;
System.out.println(p.info);
}
}
sw=1;
do{
System.out.println("\n\n\n\nProcesamiento de una lista circular
simplemente enlazada\n");
System.out.println("0. Salir");
System.out.println("1. Anula lista");
System.out.println("2. Inserta un elemento a la lista");
System.out.println("3. Contenido de la lista");
System.out.print("Opcion ==> ");
opcion=Leer.datoInt();
switch(opcion){
case 0:sw=0;break;
case 1:L.anula();break;
case 2:
System.out.print("Digite valor a insertar ==> ");
x=Leer.datoInt();
L.inserta(x);
break;
case 3:
L.contenido();break;
}
}while(sw==1);
}
}
L
3 + 2 -
2 * 5 / 3 NULL
Archivo: ListaSimple.java
//programa que realiza la implementación del
//TDA lista con referencias.
ListaSimple(){
top=sig=null;
}
System.out.println("Impresion de la lista");
p=top;
while(p!=null){
System.out.print(" "+p.info);
p=p.sig;
}
System.out.println();;
}
p=top;
resp=Character.digit(p.info,10);
operador =p.sig;
op2=operador.sig;
while(operador!=null)
{
switch(operador.info)
{
case '+': resp=resp+Character.digit(op2.info,10);break;
case '-': resp=resp-Character.digit(op2.info,10);break;
case '*': resp=resp*Character.digit(op2.info,10);break;
case '/': resp=resp/Character.digit(op2.info,10);break;
}
operador=op2.sig;
if(operador!=null)
op2=operador.sig;
}
return(resp);
}
Archivo: DemoListaSimple.java
public class DemoListaSimple{
public static void main(String []args)
{
L.contenido();
//Archivo TerminoPolinomio.java
//programa que realiza la implementación del
//TDA Polinomio con referencias.
TerminoPolinomio(){
top=sig=null;
}
comienzo=top;
// Crear nuevo dato
nuevo=new TerminoPolinomio();
p=new TerminoPolinomio();
ESTRUCTURA DE DATOS EN JAVA 57
nuevo.coef=c;
nuevo.expo=e;
// Primer dato
if (comienzo==null){
comienzo=nuevo;
nuevo.sig=null;
}
else //valor antes de comienzo
if (e<comienzo.expo){
nuevo.sig=comienzo;
comienzo=nuevo;
}
else {
// Nuevo se halla entre p y q luego
// de enlazarlos
q=comienzo;
while (q!=null && (e>=q.expo)){
p=q;
q=q.sig;
}
p.sig=nuevo;
nuevo.sig=q;
}
top=comienzo;
}
if (p!=null)
{System.out.print(p.coef+"X^"+p.expo +"+");
contenido(p.sig);
}
if (p==null)
return 0;
else
return p.coef*(float)Math.pow(x,p.expo)+evalua(x,p.sig);
}
}
// Archivo DemoTerminoPolinomio.java
sw=1;
do{
System.out.println("\n\n\n\nProcesamiento de una Lista
simplemente enlazada\n");
System.out.println("0. Salir");
System.out.println("1. Anula polinomio");
System.out.println("2. Inserta un elemento al polinomio");
58 Mg. Daniel Gamarra Moreno - Mg. Abraham Gamarra Moreno
System.out.println("3. Contenido del polinomio");
System.out.println("4. Evaluacion polinomio");
}
}while(sw==1);
}
}
L1
3 6 7 9 NULL
L2
5 8 NULL
Se obtiene:
L1
3 5 6 7
8 9 NULL
L2
NULL
Utilizando la herencia se ha creado la clase Lis-
taUnir a partir de la clase ListaSimple (Para hacer
correr el programa ambas clases deben estar en el
ESTRUCTURA DE DATOS EN JAVA 59
mismo directorio o sus rutas en la variable CLASS-
PATH)
public class ListaUnir extends ListaSimple{
inicio=null;
inicio1=top;
inicio2=L2.top;
while(inicio1!=null && inicio2!=null){
if(inicio1.info>=inicio2.info){
p=inicio2;
while (p!=null && inicio1.info >= p.info){
q=p;
p=p.sig;
}
if(inicio==null){
inicio=inicio2;
q.sig=inicio1;
inicio2=p;
fin=inicio1;
inicio1=inicio1.sig;
}
else{
fin.sig=inicio2;
inicio2=p;
q.sig=inicio1;
fin=inicio1;
inicio1=inicio1.sig;
}
}
else
{
p=inicio1;
while (p!=null && inicio2.info >= p.info){
q=p;
p=p.sig;
}
if(inicio==null){
inicio=inicio1;
q.sig=inicio2;
inicio1=p;
fin=inicio2;
inicio2=inicio2.sig;
}
else{
fin.sig=inicio1;
inicio1=p;
q.sig=inicio2;
fin=inicio2;
inicio2=inicio2.sig;
}
}
}
if (inicio1!=null || inicio2!=null){
if(inicio1!=null)fin.sig=inicio1;
else fin.sig=inicio2;
}
if(inicio==null)
if(inicio1==null) inicio=inicio2;
else inicio=inicio1;
60 Mg. Daniel Gamarra Moreno - Mg. Abraham Gamarra Moreno
top=inicio;
}
while(true){
System.out.print(mensaje);
x=Leer.datoInt();
if (x==0) break;
L.inserta(x);
}
}
L1
3 6 7 9 NULL
L2
5 6 8 NULL
Se obtiene:
L1
3 5 6 7
8 9 NULL
L2
NULL
Utilizando la herencia se ha creado la clase Lis-
taUnirNoRepite a partir de la clase ListaSimple
(Para hacer correr el programa ambas clases deben
estar en el mismo directorio o sus rutas en la va-
riable CLASSPATH)
public class ListaUnirNoRepite extends ListaSimple{
inicio=null;
inicio1=top;
inicio2=L2.top;
while(inicio1!=null && inicio2!=null){
if(inicio1.info>=inicio2.info){
p=inicio2;
while (p!=null && inicio1.info >= p.info){
q=p;
p=p.sig;
}
if(inicio==null){
inicio=inicio2;
q.sig=inicio1;
inicio2=p;
fin=inicio1;
inicio1=inicio1.sig;
}
else{
fin.sig=inicio2;
inicio2=p;
q.sig=inicio1;
fin=inicio1;
inicio1=inicio1.sig;
}
}
else
{
p=inicio1;
while (p!=null && inicio2.info >= p.info){
q=p;
p=p.sig;
}
if(inicio==null){
inicio=inicio1;
q.sig=inicio2;
inicio1=p;
fin=inicio2;
inicio2=inicio2.sig;
}
else{
fin.sig=inicio1;
inicio1=p;
q.sig=inicio2;
fin=inicio2;
inicio2=inicio2.sig;
}
}
}
if (inicio1!=null || inicio2!=null){
if(inicio1!=null)fin.sig=inicio1;
else fin.sig=inicio2;
}
if(inicio==null)
if(inicio1==null) inicio=inicio2;
else inicio=inicio1;
top=inicio;
EliminaRepetido();
}
q=top;
if (q==null)
System.out.println("Lista vacia");
else{
p=q;
q=q.sig;
while (q!=null){
if (p.info==q.info){
r=q.sig;
p.sig=r;
q=r;
}else{
p=q;
q=q.sig;
}
}
}
}
while(true){
System.out.print(mensaje);
x=Leer.datoInt();
if (x==0) break;
L.inserta(x);
}
}
c1=top;
c2=L2.top;
if (c1==null)
System.out.println("lista vacia");
else{
s=c2;
while(s!=null){
q=c1;
p=null;
while(q!=null && s.info>q.info){
p=q;
q=q.sig;
r=q.sig;
}
if(s.info==q.info){
if (p==null){
p=q;
q=q.sig;
c1=q;
}else p.sig=r;
}
s=s.sig;
}
}
top=c1;
}
while(true){
System.out.print(mensaje);
x=Leer.datoInt();
if (x==0) break;
L.inserta(x);
}
64 Mg. Daniel Gamarra Moreno - Mg. Abraham Gamarra Moreno
}
q=top;
if (q==null)
System.out.println("Lista vacia");
else{
p=q;
q=q.sig;
while (q!=null){
if (p.info==q.info){
r=q.sig;
p.sig=r;
q=r;
}else{
p=q;
q=q.sig;
}
}
}
}
PROBLEMA UNO
Construir una lista enlazada circular simple por la
disciplina FIFO (cola).
PROBLEMA DOS
Dada una lista enlazada simple buscar el nodo que
contenga el dato D e insertar antes de él un nuevo
nodo con el dato E. En caso de no encontrarse se
insertará al final.
PROBLEMA TRES
Dada dos listas enlazadas ordenadas, combinarlas en
una sola lista ordenada. La nueva lista ordenada
reemplaza a las listas anteriores.
ESTRUCTURA DE DATOS EN JAVA 65
CAPITULO CUATRO
RECURSION
a) n! = n (n-1)! , si n > 0
b) 0! = 1
De acuerdo con está definición, el cálculo de fac-
torial de 4! es como sigue:
a) a*b = a, si b=1
b) a*b = a * (b-1) + a si b>1
De acuerdo con esta definición, si se desea evaluar
6 * 2 se tiene:
68 Mg. Daniel Gamarra Moreno - Mg. Abraham Gamarra Moreno
6 *3 = 6 * 2 + 6
= 6 * 1+ 6 + 6
= 6 + 6 + 6
public class producto{
public static int producto(int a, int b){
if (b==1) return(a);
else return(producto(a,b-1)+a);
}
Solución 1
public class mcd1{
public static int mcd(int a,int b){
if (b>a) return mcd(b,a);
if (b==0) return a;
else return mcd(b,a%b);
}
do{
System.out.print("Primer número : ");
n1=Leer.datoInt();
System.out.print("Segundo número: ");
n2=Leer.datoInt();
System.out.println("MCD de "+n1+" y "+n2+" es "
+mcd(n1,n2));
System.out.println();
ESTRUCTURA DE DATOS EN JAVA 69
System.out.print("Continuar (s/n)? ");
resp=Leer.datoChar();
}while(resp!='n'&& resp!='N');
}
}
Solución 2
public class mcd2{
do{
System.out.print("Primer número : ");
n1=Leer.datoInt();
System.out.print("Segundo número: ");
n2=Leer.datoInt();
System.out.println("MCD de "+n1+" y "+n2+" es "
+mcd(n1,n2));
System.out.println();
System.out.print("Continuar (s/n)? ");
resp=Leer.datoChar();
}while(resp!='n'&& resp!='N');
}
}
Solución
//Archivo TerminoPolinomio.java
//programa que realiza la implementación del
70 Mg. Daniel Gamarra Moreno - Mg. Abraham Gamarra Moreno
//TDA Polinomio con referencias.
TerminoPolinomio(){
top=sig=null;
}
comienzo=top;
// Crear nuevo dato
nuevo=new TerminoPolinomio();
p=new TerminoPolinomio();
nuevo.coef=c;
nuevo.expo=e;
// Primer dato
if (comienzo==null){
comienzo=nuevo;
nuevo.sig=null;
}
else //valor antes de comienzo
if (e<comienzo.expo){
nuevo.sig=comienzo;
comienzo=nuevo;
}
else {
// Nuevo se halla entre p y q luego
// de enlazarlos
q=comienzo;
while (q!=null && (e>=q.expo)){
p=q;
q=q.sig;
}
p.sig=nuevo;
nuevo.sig=q;
}
top=comienzo;
}
if (p!=null)
{System.out.print(p.coef+"X^"+p.expo +"+");
contenido(p.sig);
}
if (p==null)
return 0;
else
return p.coef*(float)Math.pow(x,p.expo)+evalua(x,p.sig);
}
}
sw=1;
do{
System.out.println("\n\n\n\nProcesamiento de una Lista
simplemente enlazada\n");
System.out.println("0. Salir");
System.out.println("1. Anula polinomio");
System.out.println("2. Inserta un elemento al polinomio");
System.out.println("3. Contenido del polinomio");
System.out.println("4. Evaluacion polinomio");
}
}while(sw==1);
}
}
PROBLEMA UNO
Desarrollar un procedimiento o función recursiva
para hallar las combinaciones de n números combina-
dos en grupos de r elementos. Recomendación: Utili-
ce las siguientes propiedades:
C 0n = 1
PROBLEMA DOS
Escribir un programa que utilizando una función re-
cursiva imprima los “n” numeros consecutivos. Ver
carpeta imprimen.
public class impresion {
public static void imp(int n){
if(n!=0)
{
imp(n-1);
System.out.println(n);
//imp(n-1);
}
}
public static void main(String arg[])
{
int n;
System.out.println("ingrese numero");
n=Leer.datoInt();
System.out.println("La impresion es:");
imp(n);
System.out.println("\n");
}
}
PROBLEMA TRES
Diseñar un método recursivo para encontrar las ci-
fras de un numero entero. Ver carpeta imprimen.
public class impresion3 {
public static void imp(int n){
int r;
if(n!=0)
{
r=n%10;
//System.out.print(";"+r);
imp(n/10);
System.out.println(r);
}
}
public static void main(String arg[])
{
int n;
System.out.println("ingrese numero");
n=Leer.datoInt();
System.out.println("La impresion es:");
imp(n);
System.out.println("\n");
}
}
PROBLEMA CINCO
Considere un arreglo (matriz) unidimensional de en-
teros. Escriba algoritmos recursivos para calcular:
PROBLEMA SEIS
La función de Ackerman se define en forma recursiva
para enteros no negativos de la siguiente manera:
a(m,n)=n+1 Æ si m=0
a(m,n)=a(m-1,a(m,n-1) Æ si m≠0,n ≠0
PILAS Y COLAS
5 6 NULL
Cima Fin
(Inicio)
// Utiliza la clase Leer que
// deben estar almacenadas en la misma carpeta
class pila {
int info;
pila sig;
pila inicio;
pila fin;
pila(){
inicio = fin = sig = null;
}
if(inicio==null)
System.out.println("Pila vacía");
else // Quitar del principio de la pila
inicio = inicio.sig;
}
System.out.println("impresión de la pila");
p=inicio;
while(p!=null){
System.out.println(p.info);
p=p.sig;
}
System.out.println();
}
}
int x=0,pos=0,sw,opcion;
sw=1;
do{
System.out.println("\n\n\n\nProcesamiento de una
Pila\n");
System.out.println("0. Salir");
System.out.println("1. Anula pila");
System.out.println("2. Apila");
System.out.println("3. Contenido de la pila");
System.out.println("4. Desapila");
System.out.println("5. Cima");
System.out.print("Opcion ==> ");
opcion=Leer.datoInt();
switch(opcion){
case 0: sw=0;break;
case 1: P.anula();break;
case 2: System.out.print("Valor a insertar
==>");
x=Leer.datoInt();
P.apila(x);
break;
case 3: P.contenido();break;
case 4: P.desapila();
break;
case 5:
x=P.cima();
if(x==-1)
ESTRUCTURA DE DATOS EN JAVA 77
System.out.println("Pila Vacía
");
else
System.out.println("Valor de la
cima es: "+x);
break;
}
}while(sw==1);
}
}
a, b, c, d, e
Frente Fin
Esto ocasiona que el primer elemento en entrar es
el primero en salir; de aquí el nombre de lista fi-
fo (first in, first out) que también se le da a una
cola.
5.2.1. OPERACIONES
Las operaciones básicas que caracterizan a una cola
son las siguientes:
5 6 NULL
Frente Fin
(Inicio)
// Utiliza la clase Leer que
// deben estar almacenadas en la misma carpeta
public class cola {
int info;
cola sig;
cola inicio;
cola fin;
cola(){
inicio = fin = sig = null;
}
System.out.println("impresión de la cola");
p=inicio;
while(p!=null){
System.out.print(p.info+"-->");
p=p.sig;
}
System.out.println("null");
}
}
int x=0,pos=0,sw,opcion;
sw=1;
do{
System.out.println("\n\n\n\nProcesamiento de una
cola\n");
System.out.println("0. Salir");
System.out.println("1. Anula cola");
System.out.println("2. Inserta cola");
System.out.println("3. Contenido de la cola");
System.out.println("4. Suprime cola");
System.out.println("5. Frente");
System.out.print("Opcion ==> ");
opcion=Leer.datoInt();
switch(opcion){
case 0: sw=0;break;
case 1: C.anula();break;
case 2: System.out.print("Valor a insertar
==>");
x=Leer.datoInt();
C.inserta_cola(x);
break;
case 3: C.contenido();break;
case 4: C.suprime_cola();
break;
case 5: x=C.frente();
if(x==-1)
System.out.println("Cola vacía");
else
System.out.println("Valor del frente
es: "+x);
break;
}
}while(sw==1);
}
}
ColaPromedio(){
nom="";
tia=tie=0;
inicio=fin=sig=null;
}
System.out.println("\n\nImpresión de la cola");
p=inicio;
while(p!=null){
System.out.print(p.nom+" "+p.tia+" "+p.tie+" --> ");
p=p.sig;
}
System.out.println("null");
ESTRUCTURA DE DATOS EN JAVA 81
}
while (true) {
System.out.print("Nombre (* para finalizar) ==> ");
n=Leer.datoString();
if(n.equals("*")) break;
System.out.print("Tiempo de atencion ==> ");
ta=Leer.datoFloat();
System.out.print("Tiempo de espera ==> ");
te=Leer.datoFloat();
inserta_cola(n,ta,te);
}
}
System.out.println("\n\nImpresion calculos");
p=inicio;
while(p!=null){
sumata+=p.tia;
if (p.tie>mayte) mayte=p.tie;
cant++;
p=p.sig;
}
System.out.println("Promedio de tiempo de atencion "+
sumata/cant);
System.out.println("Mayor tiempo de espera "+mayte);
}
C.leer_datos();
C.contenido();
C.calcular_prom_ta_may_te();
}
}
Cola(){
nom="";
norden=0;
tt=tii=till=0;
inicio=fin=sig=null;
}
nuevo.norden=no;
nuevo.nom=n;
nuevo.tii=ti;
nuevo.till=tll;
nuevo.tt=nuevo.till-nuevo.tii;
inserta_cola(no,n,ti,tll);
}
}
ListaSimple.java
//programa que realiza la implementación del
//TDA lista con referencias.
ListaSimple(){
top=sig=null;
}
comienzo=top;
// Crear nuevo dato
nuevo=new ListaSimple();
p=new ListaSimple();
// Primer dato
if (comienzo==null){
comienzo=nuevo;
nuevo.sig=null;
}
else //valor antes de comienzo
if (t<comienzo.tt){
nuevo.sig=comienzo;
comienzo=nuevo;
}
else {
// Nuevo se halla entre p y q luego
// de enlazarlos
q=comienzo;
while (q!=null && (t>=q.tt)){
p=q;
q=q.sig;
}
p.sig=nuevo;
nuevo.sig=q;
}
top=comienzo;
}
System.out.println("Impresion de la lista");
p=top;
while(p!=null){
System.out.print(p.nom+" "+p.tii+" "+p.till+" "+p.tt+" --> ");
p=p.sig;
}
System.out.println();;
}
MaratonAppl.java
// programa que almacena los datos de atletas de una
// competencia de maraton. Se almacena los siguientes datos en
// una cola: el tiempo de inicio, el tiempo de llegada (ambos son minutos
// transcurridos después de las 9 am). Además se debe calcular el tiempo
// transcurrido y mostrar a los atletas ordenados de menor a mayor por el
// tiempo transcurrido.
// Sólo utilice las operaciones de Lista y Cola para dar solución a este
// ejercicio.
C.leer_datos();
C.contenido();
while(C.frente()!=-1)
{
Ctemp=C.datosfrente();
norden=Ctemp.norden;
nom=Ctemp.nom;
tii=Ctemp.tii;
till=Ctemp.till;
tt=Ctemp.tt;
L.inserta(norden,nom,tii,till,tt);
C.suprime_cola();
}
L.contenido();
}
}
La ejecución es:
pila(){
inicio=fin=sig=null;
}
System.out.println("impresión de la pila");
p=inicio;
while(p!=null){
System.out.println(p.info);
p=p.sig;
}
System.out.println();
}
car=car1=car2='\0';
valid=true;
anula();
apila(car);
if (car==')' ||
car==']' ||
car=='}')
if(inicio==null)
valid=false;
else {
switch(car){
case ')':
car1='(';break;
case ']':
car1='[';break;
case '}':
car1='{';break;
}
car2=cima();
desapila();
if(car1!=car2) valid=false;
}
i++;
}
if(inicio!=null)
valid=false;
if (valid)
System.out.println("\nExpresion valida");
else
System.out.println("\nExpresion no valida");
}
}
La Clase EvaluaExpr utiliza la clase pila y analiza
una expresión:
public class EvaluaExpr{
88 Mg. Daniel Gamarra Moreno - Mg. Abraham Gamarra Moreno
public static void main(String []args){
pila P=new pila();
String expresion;
System.out.print("Expresion : ");
expresion=Leer.datoString();
P.evalua_exp(expresion);
}
}
FileReader archivo;
BufferedReader archivoIn = null;
try{
archivo=new FileReader("test.txt");
archivoIn=new BufferedReader(archivo);
while((expresion=archivoIn.readLine())!=null){
System.out.println("\n\n\nExpresion : "+expresion);
P.evalua_exp(expresion);
}
}
catch(IOException e){
System.out.println(e);
}
finally{
try{
if(archivoIn!=null)
archivoIn.close();
}
catch(IOException e){
}
}
}
}
3 10
4 4
5 Æ 5
3 10
7 7
2 2
Pila.java
// Utiliza la clase Leer que
// deben estar almacenadas en la misma carpeta
class pila {
int info;
pila sig;
pila inicio;
pila fin;
pila(){
inicio = fin = sig = null;
}
if(inicio==null)
System.out.println("Pila vacía");
else // Quitar del principio de la pila
inicio = inicio.sig;
}
System.out.println("impresión de la pila");
p=inicio;
while(p!=null){
System.out.println(p.info);
p=p.sig;
}
System.out.println();
}
p2.anula();
// reemplaza num1 de la pila con num2
while (p1.cima()!=-1 )
{
if (p1.cima()==num1)
p2.apila(num2);
else
p2.apila(p1.cima());
p1.desapila();
}
// invierte pila
p1.anula();
while (p2.cima()!=-1 )
{
p1.apila(p2.cima());
p2.desapila();
}
return p1;
}
}
Demopila.java
public class DemoPila{
public static void main(String []args)
{
pila P=new pila();
int x=0,pos=0,sw,opcion;
sw=1;
}
}while(sw==1);
}
}
Cola.java
Cola sig;
Cola inicio;
Cola fin;
Cola(){
inicio=fin=sig=null;
}
nuevo.info=n;
System.out.println("\n\nImpresion de la cola");
p=inicio;
while(p!=null){
System.out.print(p.info+" --> ");
p=p.sig;
}
System.out.println("");
}
while (true)
{
System.out.print("Ingrese numero(10000 para finalizar) ==> ");
n=Leer.datoInt();
if(n==10000) break;
inserta_cola(n);
}
}
Pila.java
class pila {
int info;
pila sig;
pila inicio;
pila fin;
pila(){
inicio = fin = sig = null;
94 Mg. Daniel Gamarra Moreno - Mg. Abraham Gamarra Moreno
}
nuevo.info = x;
// Pone al principio de la pila
if(inicio!=null) nuevo.sig = inicio;
inicio = nuevo;
if(fin==null) fin = inicio;
if(inicio==null)
System.out.println("Pila vacia");
else // Quitar del principio de la pila
inicio = inicio.sig;
}
System.out.println("impresión de la pila");
p=inicio;
while(p!=null){
System.out.println(p.info);
p=p.sig;
}
System.out.println();
}
}
DemoCola.java
public class DemoCola{
public static void main(String []args)
{
int n;
Cola C=new Cola();
Cola C1=new Cola();
Cola C2=new Cola();
C.leer_datos();
C.contenido();
while(C.frente()!=-10000)
{
n=C.frente();
C.suprime_cola();
}
P1.contenido();
P2.contenido();
C1.contenido();
C2.contenido();
}
}
ARBOLES
B C
E G
D F H
I J K L
B C
D E F G H
I J K L
Ilustración 3. Grafo.
Gráficamente puede representarse una estructura ár-
bol de diferentes formas y todas ellas equivalen-
tes; por ejemplo: se representa por medio de Dia-
gramas de Venn, por medio de anídación de parénte-
sis y por medio de grafos. Esta última representa-
ción es la que comúnmente se utiliza; y ha origina-
do el término árbol por su parecido abstracto con
el vegetal (raíz, ramas, hojas). Es de notar que en
esta representación la raíz se dibuja arriba, aun-
que en el vegetal se encuentre abajo.
Ejemplo
B C
D E F G H
I J K L
B C
D E F
G H I
6.3.1. DEFINICIONES
n1
n2
N3
……
nk
El camino n1, n2,...,nk tiene longi-
tud k-1 (igual número de aristas que
conectan los nodos)
B C D
E F G H I J K
L M N O
B C D
E F G H I J K
L M N O
A
B
E
L
F
C
G
M D
H
N
I
J
O
K
Visitar la raíz.
Visitar la raíz.
Observación:
Ejemplo Uno
B C
D E F G
InOrden : D B E A F C G
PostOrden : D E B F G C A
Ejemplo Dos
B C
D E F
G H I J
InOrden : G K D B A H E I C F J
PostOrden : K G D B H I E J F C A
// Métodos
public CNodo(){} // constructor
}
// Métodos
……………………………
}
B C
X D X X E X X F X X G X
actual=raíz;
if(actual!=null){
procesar(actual.datos);
preorden(actual.izquierdo);
preorden(actual.derecho);
}
}
actual=raíz;
if(actual!=null){
inorden(actual.izquierdo);
procesar(actual.datos);
inorden(actual.derecho);
}
}
actual=raíz;
if(actual!=null){
posorden(actual.izquierdo);
posorden(actual.derecho);
procesar(actual.datos);
}
}
120
87 140
43 99 130
22 65 93 135
56
Ejemplo
120
120
87
120 120
87 87
43 43
65
120 120
87 140 87 140
43 43 99
65 65
120 120
87 140 87 140
43 99 130 43 99 130
65 22 65
120
87 140
43 99 130
22 65
56
87 140
43 99 130
22 65 93 135
56
120 120
87 140 87 140
43 99 130 43 99 130
22 65 93 135 65 93 135
56 56
120 120
87 140 65 140
43 93 130 43 93 130
65 135 56 135
56
93 93
65 140 65 130
43 130 43 135
56 135 56
93
65 130
43
// Métodos
public CNodo(){} // constructor
}
// Buscar un nodo que tenga asociados los datos dados por obj
while(actual!=null){
if ((nComp=comparar(obj,actual.datos))==0)
return(actual.datos); // CORRECTO (nodo encontrado)
else if(nComp<0) // buscar en el subárbol izquierdo
actual = actual.izquierdo;
else // buscar en el subárbol derecho
actual = actual.derecho;
}
return null; // NO_EXISTE
}
return CORRECTO;
} // fin del bloque if (actual==null)
else // el nodo ya existe en el árbol
return YA_EXISTE;
}
CNodo actual=null;
if(nodoRaíz)
actual=raíz; // partir de la raíz
else
actual=r; // partir de un nodo cualquiera
if(actual!=null){
inorden(actual.izquierdo,false ); // visitar subárbol izq.
// Procesar los datos del nodo visitado
procesar(actual.datos);
inorden(actual.derecho,false); // visitar subárbol dcho.
}
}
CNodo actual=null;
if(nodoRaíz)
actual=raíz; // partir de la raíz
else
actual=r; // partir de un nodo cualquiera
if(actual!=null){
CNodo actual=null;
if(nodoRaíz)
actual=raíz; // partir de la raíz
else
actual=r; // partir de un nodo cualquiera
if(actual!=null){
posorden(actual.izquierdo,false ); // visitar subárbol izq.
posorden(actual.derecho,false); // visitar subárbol dcho.
// Procesar los datos del nodo visitado
procesar(actual.datos);
}
}
}
Clase CDatos
public class CDatos{
// Atributos
private String nombre;
private double nota;
// Métodos
public CDatos(){} // constructor sin parámetros
public CDatos(String nom,double n){ // constructor con parámetros
nombre = nom;
nota = n;
}
Clase Test
Esta clase premite crear el arbol binario.
// Crear un árbol binario de búsqueda
ORDENAMIENTO Y BÚSQUEDA
7.1. ORDENAMIENTO
Consiste en organizar los datos en algún orden da-
to, tal como ascendente o descendente los datos a
ordenar tienen que ser del mismo tipo como: numéri-
cos, alfabéticos, alfanuméricos, fechas.
entonces:
SEUDOCODIGO
Para i= n-2 hasta 0 incremento -1 hacer
Para j= 0 hasta i hacer
Si datos[j]>datos[j+1] entonces
cambio(datos[j],datos[j+1])
Finsi
Finpara
Finpara
SEUDOCODIGO
Para i= 1 hasta n-1 hacer
Para j=n-1 hasta i incremento -1 hacer
Si datos[j-1]>datos[j] entonces
cambio(datos[j-1],datos[j])
Finsi
Finpara
Finpara
SEUDOCODIGO
Para i=1 hasta n-1 hacer
aux=datos[i]
j=i-1
Mientras datos[j]>aux y j>0 hacer
datos[j+1]=datos[j]
j=j-1
FinMientras
Si datos[j]>aux entonces
datos[j+1]=datos[j]
datos[j]=aux
sino
datos[j+1]=aux
FinSi
FinPara
SEUDOCODIGO
Para i=0 hasta n-2 hacer
k=i
aux=datos[i]
Para j=i+1 hasta n-1 hacer
Si datos[j]<aux entonces
k=j
aux=datos[j]
FinSi
FinPara
datos[k]=datos[i]
datos[i]=aux
FinPara
D=parte_entera(9/2)=4
A0 A1 A2 A3 A4 A5 A6 A7 A8
Secuencia inicial 3 2 4 6 7 3 5 1 1
1era Comparación 3 2 4 1 1 3 5 6 7
2da Comparación 1 2 4 1 3 3 5 6 7
DISTANCIA DE COMPARACIÓN:
D=parte_entera(4/2)=2
A0 A1 A2 A3 A4 A5 A6 A7 A8
Secuencia inicial 1 2 4 1 3 3 5 6 7
1era Comparación 1 2 4 1 3 3 5 6 7
2da Comparación 1 1 3 2 4 3 5 6 7
DISTANCIA DE COMPARACIÓN:
D=parte_entera(2/2)=1
A0 A1 A2 A3 A4 A5 A6 A7 A8
Secuencia inicial 1 1 3 2 4 3 5 6 7
1era Comparación 1 1 2 3 3 4 5 6 7
SEUDOCODIGO
d=n
Repetir
d=Parte_entera(d/2)
Repetir
sw=0
i=0
Repetiir
i=i+1
Si a[i]>a[i+d] entonces
cambio(a[i],a[i+d])
sw=1
Finsi
Hasta i+d=n
Hasta sw=0
Hasta d=1
1er Paso 55 86 3 10 23 12 67 59 47 31 24
2do Paso 35 24 3 10 23 12 31 47 59 67 86
<>
3er Paso 27 24 3 10 23 12 31 47 59 67 86
<> <>
4to Paso 18 24 3 10 23 12 31 47 59 67 86
<> <>
5to Paso 11 12 3 10 23 24 31 47 59 67 86
<> <>
6to Paso 6 10 3 12 23 24 31 47 59 67 86
<> <> <> <> <>
7to Paso 23 3 10 12 23 24 31 47 59 67 86
<> <> <> <> <> <> <>
8vo Paso 72 3 10 12 23 24 31 47 59 67 86
<> <> <> <> <> <> <> <>
9no Paso 63 3 10 12 23 24 31 47 59 67 86
<> <> <> <> <> <> <> <> <> <>
Orden final 3 10 12 23 24 31 47 59 67 86
SEUDOCODIGO
quicksort(data[],inf,sup)
/* data es el arreglo a ordenar
inf y sup son los indices izquierdo
y derecho respectivamente que definen
la porción del arreglo a ordenar */
INICIO
left=inf;
right=sup;
half=data[parte_entera((left+right)/2)];
Mientras left<right hacer
Mientras data[left]<half y
left<sup hacer
left++;
FinMientras
Mientras half<data[right] y
right>inf)
right--;
FinMientras
Si left<right entonces
cambio(data[left],data[right])
FinSi
left=left+1
right=right-1
FinMientras
Si inf<right entonces
quicksort(data, inf, right)
FinSi
Si left<sup entonces
quicksort(data, left, sup)
FinSi
FIN
Clase Ordenamiento
public class Ordenamiento extends ArregloUni{
public void burbuja_der_izq(){
int i,j;
for(i=1;i<=n-1;i++){
aux=a[i];
j=i-1;
while (a[j]>aux && j>0){
a[j+1]=a[j];
j=j-1;
}
if(a[j]>aux){
a[j+1]=a[j];
a[j]=aux;
}
else a[j+1]=aux;
};
}
for(i=0;i<=n-2;i++){
k=i;
ESTRUCTURA DE DATOS EN JAVA 131
aux=a[i];
for(j=i+1;j<=n-1;j++)
if(a[j]<aux){
k=j;
aux=a[j];
}
a[k]=a[i];
a[i]=aux;
}
}
d=n;
do{
d=d/2;
do{
sw=0;
i=-1;
do{
i++;
if(a[i]>a[i+d]){
cambio(a,i,i+d);
sw=1;
}
} while(i+d!=n);
} while(sw!=0);
} while(d!=1);
}
left=inf;
right=sup;
half=data[(left+right)/2];
while (left<right){
while(data[left]<half && left<sup) left++;
while(half<data[right] && right>inf) right--;
if (left<right) cambio(data,left,right);
left++;
right--;
}
if (inf<right) quicksort(data, inf, right);
if (left<sup) quicksort(data, left, sup);
}
t=a[pos1];
a[pos1]=a[pos2];
a[pos2]=t;
}
}
Clase DemoOrdenamiento
public class DemoOrdenamiento{
public static void main(String []args){
Ordenamiento vector=new Ordenamiento();
int sw,opcion;
vector.ingreso();
sw=1;
132 Mg. Daniel Gamarra Moreno - Mg. Abraham Gamarra Moreno
do{
System.out.println(
"\n\n\n\nSeleccione el algoritmo de ordenamiento\n");
System.out.println("0. Salir");
System.out.println("1. Burbuja de derecha a izquierda");
System.out.println("2. Burbuja de izquierda a derecha");
System.out.println("3. Inserción directa (Baraja)");
System.out.println("4. Seleccion directa");
System.out.println("5. Método de shell");
System.out.println("6. Ordenamiento rápido");
System.out.print("Opcion ==> ");
opcion=Leer.datoInt();
if(opcion>0){
System.out.println("Arreglo antes de ordenar");
vector.reporte();
}
switch(opcion){
case 0: sw=0;break;
case 1: vector.burbuja_der_izq();break;
case 2: vector.burbuja_izq_der();break;
case 3: vector.baraja();break;
case 4: vector.seleccion_directa();break;
case 5: vector.shell();break;
case 6: vector.quicksort(vector.a,0,vector.n-1);break;
}
if(opcion>0){
System.out.println("Arreglo despues de ordenar");
vector.reporte();
}
}while(sw==1);
}
}
Ejemplo
Ejemplo
F1:
Partición inicial
F2: 15,18, 14, 40,51,93, 26,64, 13
F3: 7,75, 13,43, 75, 27
Primera fusión-partición
F : 7,15,18,75, 26,27,64
F1: 13,14,40,43,51,75,93, 13
Segunda fusión-partición
F2: 7,13,14,15,18,40,43,51,75,75,93
F3: 13,26,27,64
Tercera fusión-partición
F :
7,13,13,14,15,18,26,27,40,43,51,64,75,75,93
F1:
Ejemplo
Primera partición
F0: 40
F1: 51
F2:
F3: 13,43,93,13
F4: 14,64
F5: 15,75,75,
F6: 26
F7: 07,27
F8: 18
F9:
Primera concatenación:
F:
40,51,13,43,93,13,14,64,15,75,75,26,07, 27,18
Segunda partición
F0: 07
F1: 13,13,14,15,18
F2: 26,27
F3:
F4: 40,43
F5: 51
F6: 64
F7: 75,75
F8:
F9: 93
Segunda concatenación:
F:
07,13,13,14,15,18,26,27,40,43,51,64,75,
75,93
7.8.1. DEFINICIONES
a. Búsqueda secuencial
b. Búsqueda binaria
SEUDOCODIGO
El siguinete algoritmo retorna el indice en el
arreglo donde es encontrado el “dato”, caso contra-
rio retorna -1.
i=0;
Mientras (dato<>vec[i]) y (i<n) hacer
i=i+1
FinMientras
Si dato=vec[i] entonces
posicion=i
Sino
posicion=-1
FinMientras
SEUDOCODIGO
El siguiente algoritmo retorna la posición del ele-
mento que coincide con el buscado o -1 si no esta
en el vector.
inf=0
sup=n-1
sw=0
Mientras (sup>inf) y (sw=0) hacer
cen=Parte_entera((sup+inf)/2)
Si dato>datos[cen] entonces
inf=cen+1
Sino
si dato<datos[cen] entonces
sup=cen-1
Sino
sw=1
Finsi
FinSi
FinMientras
Si sw=1 entonces
posicion=cen
Sino
posicion=-1
Finsi
Clase Búsqueda
public class Busqueda extends ArregloUni{
public int busqueda_secuencial(int dato){
int i,posicion;
i=0;
while(dato!=a[i] && i<n) i++;
if (dato==a[i]) posicion=i;
else posicion=-1;
return posicion;
}
inf=0;
sup=n-1;
sw=0;
ESTRUCTURA DE DATOS EN JAVA 141
while(sup>=inf && sw==0){
cen=(sup+inf)/2;
if(dato>a[cen]) inf=cen+1;
else if(dato<a[cen]) sup=cen-1;
else sw=1;
}
if(sw==1) posicion=cen;
else posicion=-1;
return posicion;
}
left=inf;
right=sup;
half=data[(left+right)/2];
while (left<right){
while(data[left]<half && left<sup) left++;
while(half<data[right] && right>inf) right--;
if (left<right) cambio(data,left,right);
left++;
right--;
}
if (inf<right) quicksort(data, inf, right);
if (left<sup) quicksort(data, left, sup);
}
t=a[pos1];
a[pos1]=a[pos2];
a[pos2]=t;
}
}
Clase DemoBusqueda
public class DemoBusqueda{
public static void main(String []args){
Busqueda vector=new Busqueda();
int sw,opcion,x=0,pos=0;
vector.ingreso();
sw=1;
do{
System.out.println("\n\n\n\nSeleccione el algoritmo de
Busqueda\n");
System.out.println("0. Salir");
System.out.println("1. Busqueda secuencial");
System.out.println("2. Búsqueda binaria");
System.out.print("Opcion ==> ");
opcion=Leer.datoInt();
if(opcion>0){
System.out.print("Elemento a buscar: ");
x=Leer.datoInt();
}
switch(opcion){
case 0: sw=0;break;
case 1:
System.out.println("Contenido del arreglo");
vector.reporte();
pos=vector.busqueda_secuencial(x);
break;
case 2:
142 Mg. Daniel Gamarra Moreno - Mg. Abraham Gamarra Moreno
vector.quicksort(vector.a,0,vector.n-1);
System.out.println("Contenido del arreglo (ordenado)");
vector.reporte();
pos=vector.busqueda_binaria(x);
break;
}
if(opcion>0)
if(pos!=-1)
System.out.println("Esta en la posición: "+pos);
else
System.out.println("No se encuentra en el arreglo");
}while(sw==1);
}
}