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
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP