Java Binary Search Example
The simplest code I could think of to show a binary search in Java.
-----------------------------CODE-------------------------------------------
import java.util.Random;
public class binary
{
public static void main(String args[])
{
// BUILD ARRAY OF RANDOM NUMBERS
int[] number = new int[100];
Random rand = new Random();
for(int x=0; x<number.length; x++)
number[x]=rand.nextInt(10);
//DISPLAY OUTPUT OF BINARY SEARCH
System.out.println("FOUND AT POSITION : "+BinarySearch(number, 6));
}
private static int BinarySearch(int number[], int target)
{
int low=0;
int middle;
int high=number.length-1;
//DO SEARCH
while (low<=high)
{
middle=(low+high)/2;
if (target==number[middle])
{
return middle;
}
else if (target<number[middle])
high=middle-1; //SEARCH LOWER HALF
else
low=middle+1; //SEARCH UPPER HALF
}
return -1;///target not found
}
}
No comments:
Post a Comment