码迷,mamicode.com
首页 > 编程语言 > 详细

关于java的binarySearch()方法(转)

时间:2018-04-14 23:22:23      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:index   种类型   二分   arch   无法   rgs   baidu   class   targe   

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
*/

关于java的binarySearch()方法(转)

标签:index   种类型   二分   arch   无法   rgs   baidu   class   targe   

原文地址:https://www.cnblogs.com/cr-zj/p/8836141.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!