• Java 資料結構教程

在陣列中搜索元素



您可以使用多種演算法搜尋陣列元素,例如,讓我們討論線性搜尋演算法。

線性搜尋是一種非常簡單的搜尋演算法。在這種型別的搜尋中,會對所有專案進行順序搜尋。檢查每個專案,如果找到匹配項,則返回該特定專案,否則搜尋將繼續到資料集合的末尾。

演算法

Step 1 - Set i to 1.
Step 2 - if i > n then go to step 7.
Step 3 - if A[i] = x then go to step 6.
Step 4 - Set i to i + 1.
Step 5 - Go to Step 2.
Step 6 - Print Element x Found at index i and go to step 8.
Step 7 - Print 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("Index of the required element is :"+ i);
         }
      }
   }
}

輸出

Index of the required element is :3
廣告

© . All rights reserved.