Created
February 25, 2011 15:54
-
-
Save aajjbb/843982 to your computer and use it in GitHub Desktop.
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 com.algorithims | |
import java.util.Arrays; | |
import java.util.Random; | |
import java.util.Scanner; | |
public class BinarySearch { | |
Random random; | |
Scanner input; | |
int[] num; | |
public BinarySearch() { | |
random = new Random(); | |
num = new int[11]; | |
input = new Scanner(System.in); | |
for (int i = 0; i < num.length; i++) { | |
num[i] = random.nextInt(30); | |
} | |
Arrays.sort(num); | |
} | |
public void search() { | |
print(); | |
int low = 0; | |
int high = num.length; | |
int mid = (low + high) / 2; | |
System.out.println("\nDigite o Numero que Deseja Encontrar"); | |
int find = input.nextInt(); | |
while (low <= high) { | |
if (num[mid] == find) { | |
System.out.println("O numero requsitado foi " + num[mid] + " no indice " + mid); | |
break; | |
} else if (num[mid] > find) { | |
high = mid; | |
} else { | |
low = mid; | |
} | |
mid = (low + high) / 2; | |
} | |
} | |
public void print() { | |
for (int i = 0; i < num.length; i++) { | |
System.out.print(num[i] + " "); | |
} | |
} | |
public static void main(String[] args) { | |
new BinarySearch().search(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment