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("找到的元素索引为:"+ i);
         }else{
            System.out.println("Element not found");
         }
      }
   }
}

输出结果

找到的元素索引为:3