Java Algorithm: sequential search (with and without monitoring posts)

Source: Internet
Author: User

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

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.