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

更新時間:2020 年 3 月 13 日

6 千多個瀏覽

開啟您的 職業生涯

完成課程後獲取認證

開始吧
廣告
© . All rights reserved.