大家好,我之前谈到了二进制搜索算法的工作原理,并分享了在Java中实现二进制搜索的代码。 在那篇文章中,有人问我是否还存在其他搜索算法? 如果数组中的元素未排序,又如何使用二进制搜索算法,该如何搜索呢? 为了回答他的问题,我提到了线性搜索算法,它是二进制搜索的前身。 通常,在二进制搜索算法之前进行讲授,因为二进制搜索比线性搜索快 。 但是,没关系,您仍然可以学习此有用的算法来搜索数组或链接列表中的项目。 线性搜索或顺序搜索是一种用于在列表中查找特定值的方法,该方法包括以下步骤:一次检查每个元素,然后依次检查直到找到所需的元素。

线性搜索算法是最简单的。 对于n个项目的列表,最好的情况是值等于列表的第一个元素,在这种情况下,只需要一个比较即可。 最坏的情况是该值不在列表中(或在列表末尾仅出现一次),在这种情况下,需要进行n次比较。

对于线性搜索,最坏的性能情况是它必须遍历整个集合,这是因为该项目是最后一个项目,或者因为找不到该项目。

换句话说,如果您的集合中有N个项目,则找到主题的最坏情况是N次迭代。 用大O表示法是O(N)。 搜索速度随着集合中项目的数量线性增长。 与二进制搜索算法不同,线性搜索不需要对集合进行排序。

数据结构和算法:使用Java深入学习” 。

这是我们的示例程序,用于在Java中实现顺序搜索算法。 这是不言自明的,但是如果您对理解代码的任何部分有任何疑问,请大喊大叫,我很乐意清除您的任何疑问。

Grokking算法

您会看到线性搜索算法的原因,因为随着数组大小或元素数量的增加,搜索速度越来越慢。

import java.util.Arrays;  import java.util.Scanner;   /**  * Java program to implement linear search algorithm in Java. It's also known as  * sequential search, because its sequentially search array for desired element.  * It's best case performance is O(1), when number is located at first index of  * array, in worst case it can take upto N array index access and N comparison.  * In Big O notation, time complexity of linear search is O(n), where n is  * number of elements in array.  *  * @author Javin  */  public class LinearSearchDemo {  
     public static void main(String args[]) {  
         int [] primes = { 2 , 3 , 5 , 7 , 11 , 13 , 17 , 19 , 23 , 29 , 31 , 37 , 41 , 43 , 47 };  
         for ( int number : primes) { 
             int index = linearSearch(primes, number); 
             if (index != - 1 ) { 
                 System.out.printf( "'%d' is found at index '%d' %n" , number, 
                          index); 
             } else { 
                 System.out.printf( "'%d' not found in array %n" , number, 
                      Arrays.toString(primes)); 
             } 
         }  
     }  
     /** 
      * Search a number in array using linear search algorithm. It's one of the 
      * simplest algorithm in programming world, which just require iterating 
      * over array and comparing each element with desired one. Once found you 
      * break the loop and return index of element. 
      * 
      * @param array 
      * @param number 
      * @return index of number in array, or -1 if not found 
      */ 
     public static int linearSearch( int [] array, int number) { 
         for ( int i = 0 ; i < array.length; i++) { 
             if (array[i] == number) { 
                 return i; 
             } 
         } 
         return - 1 ; // Number not found in array 
     }   }   Output:  is found at index '0' is found at index '2' '0'  '3' is found at index '1'  is found at index '2' is found at index '5' '2'  is found at index '3' is found at index '7' '3'  is found at index '4' is found at index '11' '4'  is found at index '12' is found at index '41' '12'  is found at index '13' is found at index '43' '13'  is found at index '14' is found at index '47' '14'

就是这样