Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class ConjuntoTabla implements Conjunt {
- //Descripción general: Implementación en forma de tabla de enteros
- //Tabla de enteros ordenada de forma creciente
- private int _tablaInt[];
- public ConjuntoTabla() {
- this._tablaInt = new int [0];
- }
- private void setElem(int i, int n) {
- _tablaInt[i] = n;
- }
- private int getElem(int i) {
- return _tablaInt[i];
- }
- //Cierto si n pertenece al conjunto
- public boolean pertenece(int n) {
- int medio, izq = 0, der = this.nelem()-1;
- boolean encontrado = false;
- while (!encontrado && izq <= der) {
- medio = (izq + der)/2;
- if (n < getElem(medio)) der = medio -1;
- else if (n > getElem(medio)) izq = medio + 1;
- else encontrado = true;
- }
- return encontrado;
- }
- public int nelem() {
- return (_tablaInt.length);
- }
- @Override
- public String toString() {
- String s = "";
- for (int i=0; i<nelem(); i++) {
- if (i==0) s = s+getElem(i);
- else s = s + "," + getElem(i);
- }
- return "[" + s + "]";
- }
- }
- //Se ha añadido n al conjunto ordenadamente
- public void insertar(int n)
- {
- if (!this.pertenece(n)) {
- int i = this.nelem();
- int aux[] = new int[i+1];
- for (int j=0; j < i; j++) {
- aux[j] = getElem(j);
- }
- //Busca la posición donde se debe insertar n
- while (i > 0 && n < getElem(i-1)) {
- aux[i] = getElem(i-1);
- i--;
- }
- aux[i] = n;
- _tablaInt = aux;
- }
- }
- import java.util.Scanner;
- public class TestConjuntoTabla {
- //Lee dos secuencias consecutivas de enteros separadas con '#' y las
- //pone en dos conjuntos
- public static void main(String argv[]) throws Exception {
- Scanner s = new Scanner(System.in);
- Conjunto c1 = new ConjuntoTabla();
- Conjunto c2 = new ConjuntoTabla();
- System.out.println("Introducir dos secuencias de enteros, separadas por el símbolo: #");
- while (s.hasNextInt())
- c1.añadir(s.nextInt());
- s.next(); // Salta '#'
- while (s.hasNextInt())
- c2.añadir(s.nextInt());
- System.out.println("nc1: " + c1);
- System.out.println("c2: " + c2);
- }
Add Comment
Please, Sign In to add comment