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.