Review the two implementation methods of half-lookup, and review the implementation of half-Lookup

Source: Internet
Author: User

Review the two implementation methods of half-lookup, and review the implementation of half-Lookup

Semi-query: it must be performed in an ordered table. This is important. This half-query improves the efficiency.

1. If the data value to be searched is smaller than the value of the intermediate element, the first half of the entire search range is used as the new search range.

2. If the value of the data to be searched is greater than the value of the intermediate element, the second half of the entire search range is used as the new search range.

One is the implemented badge, and the other is the directly implemented numeric value.

// A half-fold query is found and must be an ordered list.
Public class halfsearch {
Public static void mian (String args []) {


Int [] arry = {, 5 };
Int jg = halfSearch (arry, 2 );
System. out. print (jg );


}
// The first method for searching in half
Public static int halfSearch (int [] arry, int key ){
Int min = 0;
// The largest corner table;
Int max = arry. length-1;
Int mid;

While (max> min ){
Mid = (min + max)/2;
If (key> mid ){
Min = mid + 1;
}
Else if (key <mid ){
Max = mid = 1;
} Else
// The returned badge is
Return mid;
}
// When it is no longer within the range, it is a cross-border regret-1
Return-1;


}
// Method 2
Public static int halfSearch_2 (int [] arry, int key ){
Int min = 0;
Int max = arry. length-1;
Int mid = (min + max)/2;
// Compare the intermediate value with the value to be searched
While (key! = Arry [mid]) {
If (key> arry [mid]) {
Min = mid + 1;
} Else if (key <arry [mid]) {
Max = mid-1;
}
// If the maximum and minimum values overlap,-1 is returned.
Else if (min> max ){
Return-1;
}
Mid = (min + max)/2;

}

Return mid;


}
}

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.