Home  >  Article  >  Java  >  How to use binarySearch in java

How to use binarySearch in java

王林
王林forward
2023-04-20 09:31:061438browse

1. Concept

Find the specified element in the sorted array through dichotomy and return the subscript of the element.

2. Note on usage

This method is a binary search method, so you need to use the sort() method to sort the array before querying. If the array is not sorted, the result is not sure. If the array contains multiple elements with a specified value, there is no guarantee which one will be found.

3. Return value

The return value type of this method is integer, and the specific return value is divided into the following two situations:

( 1) If the element exists in the array, the subscript of the element in the array

will be returned (2) If the element does not exist in the array, -(insertion point 1)

# will be returned ##The insertion point here specifically refers to: if the element exists in the array, the subscript of that element in the array

4. Example

public static void main(String[] args) {
List<Integer> lists = new ArrayList<Integer>();
lists.add(3);
lists.add(6);
lists.add(8);
lists.add(7);
lists.add(1);
// 原来的集合
System.out.println("原来的集合:");
for (Integer str : lists) {
System.out.print(str + " ");
}
 
// 对集合进行排序
Collections.sort(lists);
System.out.println("\n排序后的集合:");
for (Integer str : lists) {
System.out.print(str + " ");
}
 
// 使用binarySearch方法查找集合中的元素
int i = Collections.binarySearch(lists, 2);
System.out.println("\n2所在的位置:" + i);
 
}

The above is the detailed content of How to use binarySearch in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete