Created
February 25, 2016 23:11
-
-
Save JRGGRoberto/133b09a184e8fd8995a7 to your computer and use it in GitHub Desktop.
Pesquisa Binária
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package TesteArrayList; | |
public class Pessoa implements Comparable<Object>{ | |
private String nome; | |
private int idade; | |
public String nome(){ | |
return this.nome; | |
} | |
@Override | |
public int compareTo(Object o) { | |
Pessoa pessoAComparar = (Pessoa)o; | |
return nome.compareTo(pessoAComparar.nome); | |
} | |
public Pessoa(String nome, int idade){ | |
this.nome = nome; | |
this.idade = idade; | |
} | |
public String valor(){ | |
return "Nome: " + this.nome + ", idade: " + this.idade; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package TesteArrayList; | |
import java.util.ArrayList; | |
import java.util.Collections; | |
import java.util.Scanner; | |
public class TestePessoa { | |
static ArrayList<Pessoa> pess = null; | |
public static void addPessoa(String n, int i) { | |
pess.add(new Pessoa(n, i)); | |
Collections.sort(pess); | |
} | |
public static int pesqBinaria(String n){ | |
int min = 0; | |
int max = pess.size(); | |
int med, comp; | |
while(min!=max){ | |
med = (max + min)/2; | |
comp = n.compareTo(pess.get(med).nome()); | |
// System.out.println("Min: "+ min + "| Med: " + med + "| Max: " + max); | |
if(comp < 0) | |
max = med; | |
else if(comp > 0) | |
min = med; | |
else return med; | |
if((min==med) && ((med+1)==max)) | |
break; | |
} | |
return -1; | |
} | |
@SuppressWarnings("resource") | |
public static void Google(){ | |
String find = ""; | |
do{ | |
System.out.print("Entre com o nome: "); | |
find = new Scanner(System.in).nextLine(); | |
int id = pesqBinaria(find); | |
if(id>0) | |
System.out.println("---> Encontrado na posição "+id +"\n -> pess.get("+id +"). " + pess.get(id).valor()); | |
else | |
System.out.println("---> Não encontrado..."); | |
}while(!find.equals("bye")); | |
} | |
public static void main(String[] args) { | |
pess = new ArrayList<Pessoa>(); | |
addPessoa("bbb", 2); | |
addPessoa("zzz", 34); | |
addPessoa("aaz", 29); | |
addPessoa("ccc", 15); | |
addPessoa("ee0", 9); | |
addPessoa("012", 100); | |
addPessoa("Açç", 999); | |
addPessoa("Roberto", 1982); | |
int x = 0; | |
for (Pessoa p : pess) { | |
System.out.println((x++) +". "+p.valor()); | |
} | |
System.out.println(); | |
Google(); | |
System.out.println("\nBye!!!"); | |
System.exit(0); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment