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 教师闺蜜祝福语简短