当前位置: 代码迷 >> J2SE >> 关于二分查找的有关问题
  详细解决方案

关于二分查找的有关问题

热度:10127   发布时间:2013-02-25 21:54:40.0
关于二分查找的问题
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));
}
}

在查找2的时候,运行不出结果,百思不解,求解!
while循环的判断条件应该是<=,而不是!=。因为有可能indexL>indexR。所以死循环了。
楼主单步调试看看就明白了。 while(indexL != indexR)
改成
 while(indexL < indexR)
  相关解决方案