赞
踩
二分法检索(binary search)又称折半检索,二分法检索的基本思想是设字典中的元素从小到大有序地存放在数组(array)中
binarySearchs方法的声明如下所示
public static int binarySerach(Xxx a[],Xxx key)
java.util.Arrays.binarySearch(int[], int, int, int)
java.util.Arrays.binarySearch(double[], int, int, double)
java.util.Arrays.binarySearch(long[], long)
java.util.Arrays.binarySearch(float[], int, int, float)
java.util.Arrays.binarySearch(int[], int)
java.util.Arrays.binarySearch(byte[], int, int, byte)
java.util.Arrays.binarySearch(byte[], byte)
java.util.Arrays.binarySearch(long[], int, int, long)
java.util.Arrays.binarySearch(short[], int, int, short)
java.util.Arrays.binarySearch(char[], char)
java.util.Arrays.binarySearch(short[], short)
java.util.Arrays.binarySearch(char[], int, int, char)
java.util.Arrays.binarySearch(Object[], int, int, Object)
java.util.Arrays.binarySearch(float[], float)
java.util.Arrays.binarySearch(double[], double)
java.util.Arrays.binarySearch(Object[], Object)
Searches the specified array of ints for the specified value using the binary search algorithm. The array must be sorted (as by the sort(int[]) method) prior to making this call. If it is not sorted, the results are undefined. If the array contains multiple elements with the specified value, there is no guarantee which one will be found.
Parameters:
a - the array to be searched
key - the value to be searched for
Returns:
index of the search key, if it is contained in the array; otherwise, (-(insertion point) - 1). The insertion point is defined as the point at which the key would be inserted into the array: the index of the first element greater than the key, or a.length if all elements in the array are less than the specified key. Note that this guarantees that the return value will be >= 0 if and only if the key is found.
使用二分搜索法来搜索指定的 Xxx型数组,以获得指定的值。必须在进行此调用之前对数组进行排序(通过 sort(Xxx[]) 方法)。如果没有对数组进行排序,则结果是不确定的。如果数组包含多个带有指定值的元素,则无法保证找到的是哪一个。
import java.util.Arrays;
public class test {
public static void main(String[] args){
int[]a={1,2,3,4,6,8,52,3};
Arrays.sort(a);
for(int i=0;i<8;i++){
System.out.print(a[i]+" ");
}
System.out.println();
int x1 =Arrays.binarySearch(a, 7);
int x2 =Arrays.binarySearch(a, 7);
System.out.print("x1="+x1+" ");
System.out.println("x2="+x2);
}
}
运行结果为x1=4 为位置下标
x2=-6 为 (-(插入点) - 1)
Sorts the specified array into ascending numerical order.
Implementation note: The sorting algorithm is a Dual-Pivot Quicksort by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm offers O(n log(n)) performance on many data sets that cause other quicksorts to degrade to quadratic performance, and is typically faster than traditional (one-pivot) Quicksort implementations.
Parameters:
a - the array to be sorted
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。