[Java]
Package Ceshi;
Public class seqSearch {
/**
* @ Param args
*/
/*
Sequential search is also called linear search;
Basic Idea: Start from finding one end of the table and compare the value K with the keyword one by one at the other end. If the key is found, the search is successful;
The position of the record in the table is given. If the entire table has not found the same keyword as the K value after detection, the search fails;
Advantage: there is no requirement for data storage in tables. For linked lists, you can only perform sequential searches;
Disadvantage: When the n value is large, the average search length is large and the efficiency is low;
*/
// In the case of no monitoring record, the subscript sequence number of the object is returned if the query is successful, and-1 is returned if the query fails.
Int SeqSearch (int r [], int n, int k)
{
Int I = 0;
While (I <n & r [I]! = K)
I ++;
If (I <n)
Return I;
Else
Return-1;
}
// When there is a monitoring record, define one more unit to store the elements to be searched. In this way, each loop only needs to compare the elements and does not need to compare whether the subscript is out of bounds.
// If the query succeeds, the subscript sequence number of the object is returned. If the query fails,-1 is returned.
Int SeqSearch2 (int r [], int n, int k)
{
Int I = 0;
R [n-1] = k;
While (r [I]! = K)
I ++;
If (I <n)
Return I;
Else
Return-1;
}
Public static void main (String [] args ){
SeqSearch sq = new seqSearch ();
Int r [] = {1, 2, 3, 4, 5 };
System. out. println (sq. SeqSearch (r, 5, 3 ));
System. out. println (sq. SeqSearch2 (r, 5, 3 ));
}
}