日期:2014-05-20  浏览次数:20811 次

关于折半查找的疑问
[code=C/C++][/code]//折半查找的两种方法
class HalfSearchDemo
{
public static void main (String [] args)
{
String aa = "abcdefhi";
int index = halfSearch(aa,'i');//我什么我字符串里的前面的每个字符都能查找到而最后一个'i'却不能?
System.out.println(index);
}
public static int halfSearch(String aa,char key)
{
int max=aa.length()-1;
int min = 0;
int mid = (max+min)>>1;
while (aa.charAt(mid)!=key)
{
int num = new Character (key).compareTo(new Character (aa.charAt(mid)));
if(num>0) 
min = (mid+1);

else if(num<0)
max=(mid-1);

mid = (max+mid)>>1;

if (min>max)
return -1;
}
return mid;
}
}
//第二种方法
//class HalfSearchDemo
//{
// public static void main (String [] arga)
// {
// String aa = "abcdefhik";
// int num = halfSearch(aa,'k');
// System.out.println (num);
// }
// public static int halfSearch (String aa , char key)
// {
// int max = aa.length()-1;
// int min = 0;
// int mid;
// while (min<=max)//等于的原因是长度是一呢?
// {
// mid = (min+max)>>1;
// int num = new Character (key).compareTo(new Character (aa.charAt(mid)));
// if (num>0)
// min = mid+1;
// else if (num<0)
//
// max = mid-1;
// else 
// return mid;
//
//
// }
// return -1;
// }
//}
我的问题是aa字符串唯独最后一个查找不出来,求解

------解决方案--------------------
//我什么我字符串里的前面的每个字符都能查找到而最后一个'i'却不能?
循环中的这句话应该写错了吧?
mid = (max+mid)>>1;
是否应为:
mid = (max+min)>>1;