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
热门推荐
10 财运虎年祝福语简短语
11 单亲爸爸春节祝福语简短
12 狗狗上厕所训练
13 植物种植祝福语简短
14 翻译考试祝福语朋友简短
15 个人周年庆简短祝福语
16 狗狗怎么训练
17 分别祝福语简短搞笑英文
18 生日广州男生祝福语简短