Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.Scanner;
- public class BinSearchNew {
- public static void main(String[] args){
- ArrayList<Integer> lista = new ArrayList<Integer>();
- Scanner x = new Scanner(System.in);
- BinSearchNew sr = new BinSearchNew();
- int mov=0;
- for(int m=0; m<100; m++){
- lista.add((int)(Math.random()*200)+1);
- }
- sr.Ordena(lista);
- for(int m=0; m<100; m++){
- System.out.print(lista.get(m)+" ");
- }
- sr.Bin(lista, mov, x.nextInt());
- }
- public void Bin(ArrayList<Integer> lista, int mov, int id) {
- if(lista.size()>0){
- int piv = (lista.size()%2 == 0) ? (lista.size()/2)-1 : lista.size()/2;
- if(id == lista.get(piv)){
- System.out.println("Econtrado en "+mov);
- }else if(id < lista.get(piv)){
- int dif = (lista.size())-piv;
- for(int i=0; i<dif; i++){
- lista.remove(lista.size()-1);
- }
- mov++;
- Bin(lista, mov, id);
- }else if(id > lista.get(piv)){
- for(int y=0; y<= piv; y++){
- lista.remove(0);
- }
- mov++;
- Bin(lista, mov, id);
- }
- }else{
- System.out.println("No encontrado");
- }
- }
- public void Ordena(ArrayList<Integer> f){
- int tmp;
- for(int i=0; i<f.size()-1; i++){
- for(int j=i; j<f.size(); j++){
- if(f.get(j)<f.get(i)){
- tmp = f.get(i);
- f.set(i, f.get(j));
- f.set(j, tmp);
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement