[Data structure and algorithm] sequential search

Source: Internet
Author: User
  • Basic Ideas

Sequential search is the simplest Search Method. Starting from the end of a linear table, the keywords of each record are compared with the given values in sequence.

  • Code Implementation

/*** Source code name: seqsearch. java * Date: 2014-08-13 * program function: sequential query * copyright: [email protected] * a2bgeek */public class seqsearch {public static int seqsearch (INT [] In, int key) {int length = in. length; int I; for (I = 0; I <length & in [I]! = Key; I ++); if (I <length) {return I;} else {return-1 ;}} public static int seqsearchopt (INT [] In, int key) {int [] innew = extendarraysize (in, key); int length = innew. length; int I; for (I = 0; innew [I]! = Key; I ++); if (I <length) {return I;} else {return-1 ;}} public static int [] extendarraysize (INT [], int key) {int [] B = new int [. length + 1]; B [. length] = key; system. arraycopy (A, 0, B, 0,. length); return B;} public static void main (string [] ARGs) {int [] testcase = {4, 5, 8, 0, 9, 1, 3, 2, 6, 7}; int key = (INT) (math. random () * 10); system. out. println ("Key is" + key); long starttime = system. nanotime (); // int Index = seqsearch (testcase, key); int Index = seqsearchopt (testcase, key); long endtime = system. nanotime (); system. out. println ("running:" + (endtime-starttime) + "ns"); system. out. println ("index is" + index );}}

  • Additional instructions

The most important optimization point of sequential search is the loop process. seqsearchopt was originally written for the purpose of optimization. Because the comparison conditions of each loop become fewer, the efficiency can certainly be improved. If it is implemented in C language, there is no problem, but Java does not support static Array Extension, so the efficiency is not improved.

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.