Binary Search/binary search algorithm, Binary Search Algorithm

Source: Internet
Author: User

Binary Search/binary search algorithm, Binary Search Algorithm

Binary Search, also known as semi-query, has the advantage of a small number of times, fast query speed, and good average performance. Its disadvantage is that the table to be queried is an ordered table and it is difficult to insert or delete data. Therefore, the half-fold lookup method is suitable for searching frequently ordered lists without frequent changes. First, assume that the elements in the table are arranged in ascending order and the keywords recorded in the middle of the table are compared with the search keywords. If the two are the same, the search is successful; otherwise, the table is divided into the first and last sub-tables by using the intermediate position record. If the keyword recorded in the middle position is greater than the search keyword, the former sub-table is further searched. Otherwise, the latter sub-table is further searched. Repeat the preceding process until you find a record that meets the conditions to make the search successful, or until the child table does not exist, the search fails.

Class Program {static void Main (string [] args) {int [] array = new [] {23, 98,234,765,974,867,867 86, 145432,867 6343, 9999999 }; // destination array int findValue = 145432; // Number of queried consoles. writeLine (BinarySearch (array, findValue, 0, array. length-1 )? "The number to be searched exists in the array": "The number to be searched does not exist in the array"); Console. readKey () ;}/// <summary> /// Binary Search/semi-query (divide the rule, recursion, the target array must be an ordered sequence ), the algorithm complexity is o (log (n), and n represents the length of the target array) /// </summary> /// <param name = "sources"> target array </param> /// <param name = "findValue"> Number of target searches </ param> /// <param name = "low"> interval minimum index </param> /// <param name = "high"> Interval Maximum index </param> // /<returns> true: yes, false, no </returns> private static bool BinarySearch (int [] sources, int f IndValue, int low, int high) {// not found, end recursion if (low> high) return false; // half-lookup median index: (a + B) /2 indicates the arithmetic mean, that is, the midpoint int middleIndex = (low + high) % 2 = 0? (Low + high)/2: (low + high)/2 + 1; if (findValue> sources [middleIndex]) {// greater than the intermediate value, in the interval [middleIndex + 1, high] recursive query continues return BinarySearch (sources, findValue, middleIndex + 1, high);} if (findValue <sources [middleIndex]) {// less than the intermediate value, in the interval [low, middleIndex-1] recursive query of return BinarySearch (sources, findValue, low, middleIndex-1);} // findValue equals to sources [middleIndex], locate, terminate recursive return true ;}}

 


Specific Binary Search Algorithm

The half-lookup method is also called the binary lookup method. It fully utilizes the order relationship between elements and adopts the grouping policy. In the worst case, it can use O (log n) to complete the search task. The basic idea is to divide n elements into two halves with roughly the same number. Take a [n/2] for comparison with x to be searched, if x = a [n/2], locate x and terminate the algorithm. If x <a [n/2], we only need to search for x in the left half of array a (Here we assume that the array elements are in ascending order ). If x> a [n/2], we only need to search for x in the right half of array. Binary Search is widely used and easy to understand. However, it is not easy to write a correct binary search algorithm. The first binary search algorithm appeared as early as 1946, but the first fully correct binary search algorithm did not appear until 1962. In his book Writing Correct Programs, Bentley wrote that 90% of computer experts cannot write completely Correct binary search algorithms within two hours. The key to the problem is to accurately define the boundary of each search range and determine the termination conditions, and correctly summarize the various situations of parity, in fact, after sorting it out, we can find that its specific algorithm is very intuitive. We can use C ++ to describe it as follows:

Template <class Type>

Int BinarySearch (Type a [], const Type & x, int n)

{

Int left = 0;

Int right = n-1;

While (left <= right ){

Int middle = (left + right)/2;

If (x = a [middle]) return middle;

If (x> a [middle]) left = middle + 1;

Else right = middle-1;

}

Return-1;

}

Template Function BinarySearch in a [0] <= a [1] <=... <= a [n-1] x is searched for n elements in ascending order. If x is found, the position in the array is returned; otherwise,-1 is returned. It is easy to see that each execution of A while LOOP reduces the size of the array to be searched by half. Therefore, the time complexity of the entire algorithm in the worst case is O (log n ). When the data volume is large, its linear search performance is clear in terms of time complexity.

Data Structure sequential search algorithm and semi-query algorithm

Answer:
Search key = 41 algorithms: half-lookup comparison times: 3
Search algorithms with key = 35: sequential search comparison times: 6
Code for implementing the sequential search algorithm:
Int SequenceSearch (int a [], int n, int key)
{
Int I = 0, cnt = 0;
For (I = 0; I <n; I ++)
{
Cnt ++;

If (a [I] = key)
{
Printf ("\ nSequencial Search compare times: % d", cnt );
Return key;
}
}
Return-1;
}
L half-fold Search Algorithm Implementation Code:
Int BinarySearch (int a [], int n, int key)
{
Int low = 0, high = n-1, mid = 0;
Int cnt = 0;
While (low <= high)
{
Cnt ++;
Mid = (low + high)/2;
Printf ("\ ncompare % d with % d", a [mid], key );
If (a [mid] = key)
{
Printf ("\ nSequencial Search compare times: % d", cnt );
Return key;
}
If (a [mid]> key)
{
High = mid-1;
}
Else
{
Low = mid + 1;
}
}
Return-1;
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.