java-二分查找
package com.day5.test;
public class Test4 {
/**
* @param args
* 二分查找,查找元素的索引
* 前提:数组元素有序
*/
public static void main(String[] args) {
int[] arr={1,2,3,4,5,6,7,8,9};
int m=getIndex(arr,6);
System.out.println(m);//5
}
public static int getIndex(int[] arr,int value)
{
int min=0;
int max=arr.length-1;
int mid=(min+max)/2;
while(arr[mid]!=value)
{
if(arr[mid]<value)
{
min=mid+1;
}
else if(arr[mid]>value)
{
max=mid-1;
}
mid=(min+max)/2;
if(min>max)
{
return (-1);
}
}
return mid;
}
}