--二分查找(折半查找):数组有序
public static int getIndex(int[] arr,int value)
{
int maxIndex = arr.length-1;
int minIndex = 0;
int midIndex = (maxIndex+minIndex)/2;
while(arr[midIndex]!=value)
{
if(arr[midIndex]>value)
{
maxIndex = midIndex - 1;
}
else if(arr[midIndex]<value)
{
minIndex = midIndex + 1;
}
if(minIndex > maxIndex)
{
return -1;
}
midIndex = (maxIndex+minIndex)/2;
}
return midIndex;
}
|
|