关于数组查询

mtdhy 2009-09-04 05:55:07
int arr[]=new int[]{4,25,10};
Array.sort(arr);
int index=Arrays.binarySearch(arr,0,1,8);

上面代码index为何等于-2?8不是应该在10的前面吗?10的索引值不是1吗?我觉得index的值应该是-1
...全文
110 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
yanliang_xt 2009-09-04
  • 打赏
  • 举报
回复
还上粘上:

如果没有找到那么返回:

-( <i>insertion point </i>) - 1)
yanliang_xt 2009-09-04
  • 打赏
  • 举报
回复

private static int binarySearch0(int[] a, int fromIndex, int toIndex,
int key) {
int low = fromIndex; //0
int high = toIndex - 1; 0

while (low <= high) {
int mid = (low + high) >>> 1;
int midVal = a[mid];

if (midVal < key)
low = mid + 1; //1
else if (midVal > key)
high = mid - 1;
else
return mid; // key found
}
return -(low + 1); // key not found. // - 2
}


结果是-2 你可以对着源码看看。
mtdhy 2009-09-04
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 yanliang_xt 的回复:]
binarySearch
这个方法只适合在有序数组中操作。
[/Quote]

代码中有“Array.sort(arr);

排序了啊!
luxiaoshuai 2009-09-04
  • 打赏
  • 举报
回复
static int binarySearch(byte[] a, byte key)
Searches the specified array of bytes for the specified value using the binary search algorithm.
static int binarySearch(char[] a, char key)
Searches the specified array of chars for the specified value using the binary search algorithm.
static int binarySearch(double[] a, double key)
Searches the specified array of doubles for the specified value using the binary search algorithm.
static int binarySearch(float[] a, float key)
Searches the specified array of floats for the specified value using the binary search algorithm.
static int binarySearch(int[] a, int key)
Searches the specified array of ints for the specified value using the binary search algorithm.
static int binarySearch(long[] a, long key)
Searches the specified array of longs for the specified value using the binary search algorithm.
static int binarySearch(Object[] a, Object key)
Searches the specified array for the specified object using the binary search algorithm.
static int binarySearch(short[] a, short key)
Searches the specified array of shorts for the specified value using the binary search algorithm.
static
<T> int
binarySearch(T[] a, T key, Comparator<? super T> c)
Searches the specified array for the specified object using the binary search algorithm.

Sun公司的API里没有重载你这个方法啊。。。你是不是自己重写了啊。。。如果重写了,把Arrays的代码贴出来吧。
yanliang_xt 2009-09-04
  • 打赏
  • 举报
回复
binarySearch
这个方法只适合在有序数组中操作。
flyforlove 2009-09-04
  • 打赏
  • 举报
回复
你自己先看看Arrays.binarySearch的源代码,看看这个方法到底是用来做什么的。

62,621

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧