/**
* @author lautturi.com
* Java example: binary search:search element in a sorted array using java
*/
import java.util.*;
public class Lautturi {
public static void main(String[] args) {
int[] intArray = { 1,12,13,21,27,36,38,43,59,106 };
int low = 0;
int high = intArray.length-1;
int mid=-1;
int number = 59;
while(low<=high)
{
mid=low + ((high - low) / 2);;
if(intArray[mid]==number)
{
// the element index is mid;
break;
}
if(intArray[mid]<=intArray[high])
{
// Right part is sorted
if(number > intArray[mid] && number <=intArray[high])
{
low=mid+1;
}
else
{
high=mid-1;
}
}
else
{
// Left part is sorted
if(intArray[low]<=number && number < intArray[mid])
{
high=mid-1;
}
else
{
low=mid+1;
}
}
}
if(mid==-1) {
System.out.println("the element is not found in the array");
}
else {
System.out.println("found "+number+" at the position "+mid);
}
}
}
output:
found 59 at the position 8