日期:2014-05-20 浏览次数:20880 次
import java.util.Arrays;
public class ArraySearch
{
public static int search(int[] a,int value)
{
Arrays.sort(a);
int index = 0;
int indexL = 0;
int indexR = a.length - 1;
while(indexL != indexR)
{
index = (indexL + indexR) / 2;
if(value == a[index])
{
return index;
}
if(value < a[index])
{
indexR = index - 1;
}
if(value > a[index])
{
indexL = index + 1;
}
}
if(indexL == indexR)
{
if(value == a[indexL])
{
return indexL;
}
}
return -1;
}
public static void main(String[] args)
{
int[] a = new int[]{0,1,3,6,9,4,5,7,8};
System.out.println(search(a,2));
}
}