在一沓试卷,找到属于自己的那张试卷
- 一个一个地查找
- 在data数组中查找16
步骤:
- 设置索引i,在for循环中遍历索引i对应的数组
- i++,寻找==16
- 输入:数组和目标索引
- 输出:目标元素所在的索引,若不存在,返回-1
- 自己动手尝试
package com.java.week1;
/**
* Notes for class:
* * 最简单的线性查找法
* * 使用for循环遍历
* @author: Julian
* @data 2021/12/16 15:46
*/
class LinearSearch {
public int linearSearch(int[] arr,int target){
int start = 0;
int n = arr.length; //在区间[0,n)寻找对应的数
for (int i = start; i < n; i++) {
if(arr[i] == target){
return i;
}
}
return -1; //这里我忘记写了,每个函数并不是在条件中返回就行了,不满足条件的如果不写返回就相当于是严重的错误
}
}
class Test1{
public static void main(String[] args) {
int[] arr1 = {1,23,3435,56,23,12,312};
int index = new LinearSearch().linearSearch(arr1,23);
System.out.println(index);
}
}