Java - Para novatos

 
Vista:

Para novatos

Publicado por CRIS (1 intervención) el 23/05/2006 21:59:22
Necesito ejemplos de programas hechos en el lenguaje java, en el cual muestren los distintos metodos de ordenamiento y busqueda en archivos.
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder

RE:Para novatos

Publicado por Brian (33 intervenciones) el 24/05/2006 18:21:57
Gente ahi esta ese codigo utiliza ordenamiento por insercion y busqueda binaria, si tienen dudas me pueden escribir al correo a aqui

import cr.ac.ucr.algoritmos.Laboratorio0.Estudiante;
import java.io.*;

public class RAFEstudiante {

private RandomAccessFile archivo;
private final int TAMANO_REGISTRO= 40;
private final int CARNE=6;
private final int NOMBRE=30;
private final int NOTA_ADMISION=4;


public RAFEstudiante(String nombreArchivo)throws FileNotFoundException {
archivo= new RandomAccessFile(nombreArchivo,"rw");
}
/*
*Inserta un estudiante en un archivo ordenado por el carne.
*/
public void insertar(Estudiante estudiante)throws EstudianteExistenteException{
String carne=estudiante.getCarne();
String idEnArchivo;
boolean objetoIngresado;
objetoIngresado=buscar(carne);
if (objetoIngresado==true){
throw new EstudianteExistenteException();
}else if(objetoIngresado==false){
String nombre=estudiante.getNombre();
float notaAdmision=estudiante.getNotaAdmision();
RandomAccessFile temporal;
boolean insertado=false;

try{
temporal=new RandomAccessFile("temporal.dat", "rw");
temporal.setLength(0);
//coloca el puntera en la posicion inicial del archivo
archivo.seek(0);
long posAInsertar=0;
while(insertado==false){

posAInsertar=archivo.getFilePointer();

//leer el id actual
byte aCarne[]=new byte[CARNE];
archivo.readFully(aCarne);
String carneActual= String.valueOf(aCarne);

//verifico si el que esta en registro es menor o mayor
int resu=carne.compareToIgnoreCase(carneActual);

//si el id a insertar es menor que el que se encuentra almacenado
if (resu<0){
//mover los datos desde el archivo donde voy a insertar hacia el archivo donde voy ha hacer el respaldo

insertarTemporal(archivo,temporal,posAInsertar,0);

//muevo el puntero a donde se va a ingresar el archivo estudiante
archivo.seek(posAInsertar);

//escribir el carne en el archivo
archivo.writeBytes(carne);

//escribir el nombre

byte nom[]=new byte[NOMBRE];
if(nombre.length()>NOMBRE){
nombre.getBytes(0, NOMBRE, nom, 0);
}else
nombre.getBytes(0, nombre.length(), nom,0);
archivo.write(nom);

//escribir la nota de admision
archivo.writeFloat(notaAdmision);

posAInsertar=archivo.getFilePointer();

//regresa los archivos
insertarTemporal(temporal, archivo, 0,posAInsertar);
temporal.close();
insertado=true;
}else if(resu>0){
archivo.skipBytes(34);

}
}
}catch(EOFException eof){
try{
//escribir el carne en el archivo
archivo.writeBytes(carne);

//escribir el nombre

byte nom[]=new byte[NOMBRE];
if(nombre.length()>NOMBRE){
nombre.getBytes(0, NOMBRE, nom, 0);
}else
nombre.getBytes(0, nombre.length(), nom,0);
archivo.write(nom);

//escribir la nota de admision
archivo.writeFloat(notaAdmision);

}catch(IOException io){
System.out.println("Error de lectura "+io.toString());
}
}catch(FileNotFoundException fnfe){
}catch(IOException ioe){
System.out.println("Error de lectura "+ioe.toString());
}



}
}

/*
Este metodo se usa para mover el los estudiantes a este espaldo se usa para insertar
*un estudiante y su carne es menor que el ultimo en el archivo, y insertarlo
*en forma ordenada
*/
public void insertarTemporal(RandomAccessFile origen,RandomAccessFile destino,long puntoOrigen,long puntoDestino){
String carne;
try{
origen.seek(puntoOrigen);
destino.seek(puntoDestino);

do{
//leer el id en archivo de origen escribirlo en destino
byte aCarne[]=new byte[CARNE];
origen.readFully(aCarne);

destino.write(aCarne);

//leer el nombre del archivo y almacenarlo en temporal
byte aNombre[]=new byte[NOMBRE];
origen.readFully(aNombre);

destino.write(aNombre);

byte aNotaAdmision[]=new byte[NOTA_ADMISION];
origen.readFully(aNotaAdmision);

destino.write(aNotaAdmision);

}while(origen.getFilePointer()<origen.length());

}catch(EOFException eof){
}catch(IOException io){}

}//fin de insertar al temporal
/*
*Este metodo busca el estudiante y verifica su existencia Utiliza el buscar
*binario
*/
public boolean buscar(String carne){
boolean encontrado=false;

try{
int numRegistro= (int)archivo.length()/TAMANO_REGISTRO;
int inicio=0;
int fin=numRegistro-1;

while((inicio<=fin)&&(!encontrado)){
int medio=(fin+inicio)/2;

archivo.seek(medio*TAMANO_REGISTRO);
byte aCarne[]=new byte[CARNE];
archivo.readFully(aCarne);
String carneActual= String.valueOf(aCarne);

int resu=carne.compareToIgnoreCase(carneActual);

if(resu==0){
encontrado=true;
}else if (resu<0){
fin=medio-1;

}else if (resu>0){
inicio=medio+1;
}
}
}catch(IOException io){}
return encontrado;
}

/*
*Este metodo ordena los estudiantes por su nota y los retorna
*Usa el ordenamiento por insercion
*/
public String[] notaMayor(){
String resuEstu[]=new String[10];
String nombre;
int nota;

try{
int numRegistro= (int)archivo.length()/TAMANO_REGISTRO;
String aNombre[]=new String[numRegistro];
String notaAdmision[]=new String[numRegistro];
archivo.seek(0);
for(int i=0;i<=numRegistro-1;i++){

archivo.skipBytes(CARNE);

byte nom[]=new byte[NOMBRE];
archivo.readFully(nom);

String n=String.valueOf(nom);

aNombre[i]=n;

byte notaA[]=new byte[CARNE];
archivo.readFully(notaA);

String not=String.valueOf(nom);

notaAdmision[i]=not;
}
String temporalNota;
String temporalNombre;
for(int j=1;j<=numRegistro-1;j++){
for(int x=j;x>=1;x--){
int resu=notaAdmision[x].compareToIgnoreCase(notaAdmision[x-1]);
if(resu<0){
temporalNota=notaAdmision[x];
notaAdmision[x]=notaAdmision[x-1];

temporalNombre=aNombre[x];
aNombre[x]=aNombre[x-1];
}
}
}
int cont=aNombre.length-1;
for(int y=0;y<=resuEstu.length-1;y++){
resuEstu[y]=aNombre[cont];
cont--;
}
}catch(IOException io){}
return resuEstu;
}

}
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar