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.
/*** 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 );}}
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.