The arrays class of the Java array has a method -- binarysearch (). the efficiency of binary search is much higher than linear search, but it also has shortcomings. For example, the query object must be sorted. When the query object has multiple elements at the same time, only one of them can be found in binary search, and the element is not necessarily located at the beginning or the end. next, we will summarize the principles of Binary Search:
Use the Binary Search Method to search for a specified int array to obtain the specified value. The array must be sortedsort(int[])Method ). If the array is not sorted, the result is uncertain. If the array contains multiple elements with the specified value, you cannot guarantee which one is found.
Parameters:
a-Array to be searched
key-Value to be searched
Return Value:
If it is included in an array, the index of the search key is returned; otherwise(-(Insert point)-1).Insert point (MID)It is defined as the point where the key is inserted into the array: that is, the first element index that is larger than this key. If all elements in the array are smaller than the specified keyA. Length. Note that this ensures that when and only when this key is found, the returned value is greater than or equal to 0.
public static int binSearch(int a[], int key) { int mid = a.length / 2; if (key == a[mid]) { return mid; }int start = 0; int end = a.length - 1; while (start <= end) { mid = (end - start) / 2 + start; if (key < a[mid]) { end = mid - 1; } else if (key > a[mid]) { start = mid + 1; } else {return mid;}}return -mid-1;}
Principle Analysis:
Assume that there is an array in ascending order, int A []. The binary search first finds the number in the middle of the array, that is, the insert point A [Mid] is compared with the value Key to be searched.
Key> A [Mid] >>>> the key may be between a [Mid + 1] and a [end], so start = Mid + 1 continues the loop.
Key <A [Mid] >>>> the key may be between a [Mid-1] and a [start], so end = mid-1 continues the loop.
Key = A [Mid] >>> the key is found, and the insert point mid is returned.
Advantages and disadvantages:
In binary search, half of the data can be filtered out after each judgment. The efficiency is much higher than that of linear search in full traversal, but only one value can be returned. If multiple search Values exist in the array, its limitations are immediately revealed. If the array contains some elements that cannot be compared with each other (such as strings), the array cannot be sorted in the natural order of its elements, so the result is uncertain.
Therefore, when selecting a search method, you need to search for the array type and purpose (if you only search for whether the array exists or not, you can use binary search, if you look for all the positions of the number in the array, the binary method is ignored.