實施線性搜尋的 Java 程式


線性搜尋是一種非常簡單的搜尋演算法。在此類搜尋中,對所有專案逐個進行順序搜尋。檢查每個專案,如果找到匹配的專案,則返回該特定專案,否則搜尋將繼續到資料收集結束。

演算法

1.Get the length of the array.
2.Get the element to be searched store it in a variable named value.
3.Compare each element of the array with the variable value.
4.In case of a match print a message saying element found.
5.else, print a message saying element not found

舉例說明

現場演示

public class LinearSearch {
   public static void main(String args[]){
      int array[] = {10, 20, 25, 63, 96, 57};
      int size = array.length;
      int value = 63;

      for (int i=0 ;i< size-1; i++){
         if(array[i]==value){
            System.out.println("Element found index is :"+ i);
         }else{
            System.out.println("Element not found");
         }
      }
   }
}

輸出

Element found index is :3

更新時間: 13-Mar-2020

6K+ 瀏覽量

開啟你的 職業生涯

完成本課程,考取認證

入門
廣告
© . All rights reserved.