Java Algorithm: half-Lookup (recursive algorithm and non-recursive algorithm)

Source: Internet
Author: User

[Java]
Package Ceshi;
 
Public class biSearch {
 
/**
* @ Param args
*/
/*
Semi-query-when the table is an ordered table, you can use semi-query;
Basic Idea: in an ordered table, take the intermediate element as the comparison object. If the given value K is the same as the intermediate record keyword, the search is successful;
If the given value K is less than the keyword of the intermediate record, continue searching in the left half of the table;
If the given value K is greater than the keyword of the intermediate record, continue searching in the right half of the table and repeat until the search is successful/failed.
*/
 
// Half-fold searches for non-Recursive Algorithms
// If the query succeeds, the subscript sequence number of the object is returned. If the query fails,-1 is returned.
Int BiSearch (int r [], int n, int k)
{
Int low = 0;
Int high = n-1;
While (low <= high)
{
Int mid = (low + high)/2;
If (r [mid] = k)
Return mid;
Else
If (r [mid] <k)
Low = mid + 1;
Else
High = mid-1;
}
Return-1;
}
 
 
// Half-lookup Recursive Algorithm
// If the query succeeds, the subscript sequence number of the object is returned. If the query fails,-1 is returned.
Int BiSearch2 (int r [], int low, int high, int k)
{
If (low> high)
Return-1;
Else
{
Int mid = (low + high)/2;
If (r [mid] = k)
Return mid;
Else
If (r [mid] <k)
Return BiSearch2 (r, mid + 1, high, k );
Else
Return BiSearch2 (r, low, mid-1, k );
 
}
}

Public static void main (String [] args ){
BiSearch bs = new biSearch ();
Int r [] = {1, 2, 3, 4, 5 };
System. out. println (bs. BiSearch (r, 5, 5 ));
System. out. println (bs. BiSearch2 (r, 1, 5, 5 ));
}
 
}

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.