Java search algorithm (2): sequential search

Source: Internet
Author: User

Java search algorithm (2): sequential search

[What is sequential search]

Sequential search, also known as linear search, is the most basic search technology. Its search process is to compare the values one by one from the first or last record in the table, if the values are equal, the query is successful. If the last value is still different, no records are found in the table and the query is unsuccessful.


[Implement sequential search in Java]

Public class SequentialSearch {public static void main (String [] args) {Integer target = 6; Integer [] iArr = {3, 2, 6, 8, 5, 1, 7, 9}; Integer index = sequentialSearch (iArr, target); System. out. println (index);} public static

 
  
Integer sequentialSearch (T [] t, T target) {for (int I = 0; t! = Null & I <t. length; I ++) {if (t [I] = target) {return I ;}} return-1 ;}}

 

[Advantages and disadvantages of sequential search]

Advantage: the code is easy to understand

Disadvantage: when there is a large amount of data, the search efficiency is extremely low, so this algorithm is suitable for a small amount of data.


[Complexity of sequential search algorithms]

The best case for successful search is that it is found at the first position. The algorithm time complexity is O (1)

The worst case is that it is found at the last position. The time complexity is O (n)

The probability of the keyword at any position is the same, so the average number of searches is (n + 1)/2, so the final time complexity is O (n)



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.