Java 資料結構 - 線性查詢
線性查詢是一種非常簡單的搜尋演算法。在這種型別的搜尋中,會對所有專案逐一進行順序搜尋。每個專案都會被檢查,如果找到匹配項,則返回該特定專案,否則搜尋將繼續到資料集合的末尾。
演算法
線性查詢。(陣列 A,值 x)
Step 1: Get the array and the element to search. Step 2: Compare value of the each element in the array to the required value. Step 3: In case of match print element 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
廣告