binarySearch()方法详解 java

再看TIJ 的时候书中提到   未排序的数组使用binaryserach会产生很严重错误    一直想不通后来在网上找了一下得到以下结果

binarySearch()方法提供了多种重载形式,用于满足各种类型数组的查找需要,binarySearch()有两种参数类型

注:此法为二分搜索法,故查询前需要用sort()方法将数组排序,如果数组没有排序,则结果是不确定的,另外

如果数组中含有多个指定值的元素,则无法保证找到的是哪一个。

⑴.binarySearch(object[ ], object key);

如果key在数组中,则返回搜索值的索引;否则返回-1或者"-"(插入点)。插入点是索引键将要插入数组的那一点,即第一个大于该键的元素索引。

eg:

package Number;
import java.util.Arrays;
public class IntFunction
{
	public static void main (String []args)
	{
		int a[] = new int[] {1, 3, 4, 6, 8, 9};
		int x1 = Arrays.binarySearch(a, 5);
		int x2 = Arrays.binarySearch(a, 4);
		int x3 = Arrays.binarySearch(a, 0);
		int x4 = Arrays.binarySearch(a, 10);
		System.out.println("x1:" + x1 + ", x2:" + x2);
		System.out.println("x3:" + x3 + ", x4:" + x4);
	}
}
/*输出结果:
x1:-4, x2:2
x3:-1, x4:-7
*/


1.不存在时由1 开始 计数;

2.存在时由0开始计数。

⑵.binarySearch(object[ ], int fromIndex, int endIndex, object key);

如果要搜索的元素key在指定的范围内,则返回搜索键的索引;否则返回-1或者"-"(插入点)。

eg:

1.该搜索键在范围内,但不在数组中,由1开始计数;

2.该搜索键在范围内,且在数组中,由0开始计数;

3.该搜索键不在范围内,且小于范围内元素,由1开始计数;

4.该搜索键不在范围内,且大于范围内元素,返回-(endIndex + 1);(特列)

eg:

package Number;
import java.util.Arrays;
public class IntFunction
{
	public static void main (String []args)
	{
		int a[] = new int[] {1, 3, 4, 6, 8, 9};
		int x1 = Arrays.binarySearch(a, 1, 4, 5);
		int x2 = Arrays.binarySearch(a, 1, 4, 4);
		int x3 = Arrays.binarySearch(a, 1, 4, 2);
		int x4 = Arrays.binarySearch(a, 1, 3, 10);
		System.out.println("x1:" + x1 + ", x2:" + x2);
		System.out.println("x3:" + x3 + ", x4:" + x4);
	}
}
/*输出结果:
x1:-4, x2:2
x3:-2, x4:-4
*/


以上内容从 http://www.csdn123.com/html/blogs/20130809/50650.htm 转载而来



如果使用Comparator 排序了某个数组(基本类型数组无法使用Comparator 排序)在使用binarySearch 时必须提供心痛的Comparator 

例如:

public class E24 {
public static void main(String[] args){
Comparator<DataHolder> comp = new Comparator<DataHolder>() {


@Override
public int compare(DataHolder o1, DataHolder o2) {
// TODO Auto-generated method stub
return (o1.data < o2.data ? -1 : (o1.data == o2.data ? 0 : 1));

}

};
DataHolder[] a = new DataHolderWithEquals[10];
for(int i = 0; i < a.length; i++)
a[i] = new DataHolderWithEquals(i);
Arrays.sort(a, comp);
int location = Arrays.binarySearch(a, a[7], comp);
printnb("Location of " + a[7] + " is " + location);
if(location >= 0)
print(", a[" + location + "] = " + a[location]);
else
print();
location = Arrays.binarySearch(a, a[5], comp);
printnb("Location of " + a[5] + " is " + location);
if(location >= 0)
print(", a[" + location + "] = " + a[location]);

}


}



输出结果:Location of arrays.DataHolderWithEquals@a90653 is 7, a[7] =
arrays.DataHolderWithEquals@a90653
Location of arrays.DataHolderWithEquals@de6ced is 5, a[5] =
arrays.DataHolderWithEquals@de6ced


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值