Lookup Instance Usage of binarySearch in java
- 2021-08-12 02:40:27
- OfStack
In the java array, finding array elements is a relatively basic operation, and the binarySearch of the arrays class is specially implemented for specifying elements. At the same time, it also belongs to what we often call the 2-point method. So the scope of action is the sorted array. Below, we explain the concept and use attention of binarySearch, and at the same time separate its two return value situations, and finally share the search examples.
1. Concepts
Finds the specified element in an ordered array by dividing by 2, and returns the subscript of the element.
2. Use caution
This method is a 2-point search method, so the query needs to use sort () method to sort the array. If the array is not sorted, the result is uncertain. If the array contains more than one element with the 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 can be divided into the following two situations:
(1) If the element exists in the array, the subscript of the element in the array is returned
(2) If the element does not exist in the array,-(insertion point + 1) is returned
The insertion point here specifically refers to the subscript of that element in the array if it exists in the array
4. Examples
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);
// Original set
System.out.println(" Original collection: ");
for (Integer str : lists) {
System.out.print(str + " ");
}
// Sort the collection
Collections.sort(lists);
System.out.println("\n Sorted collections: ");
for (Integer str : lists) {
System.out.print(str + " ");
}
// Use binarySearch Method to find an element in the collection
int i = Collections.binarySearch(lists, 2);
System.out.println("\n2 Location: " + i);
}