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)