[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 ));
}
}