所谓的线性查找法,就是在沿着一个固定的方向,挨个查找数组中的元素,直到这个查询询到目标元素或者遍历完数组为止。
线性查找法主要有两部分组成:
1> 输入:数组和目标元素;
2> 输出:目标元素所在的索引;若不存在,返回-1;
实例代码:
public class LineTest { private LineTest() { } /** * 泛型只能接受类对象,不能接受基本类型的变量 * 不可以是基本数据类型,只能是类对象 * boolean,byte,char,short,int,long,float,double * 每个基本数据类型都有对应的包装类 * Boolean,Byte,Character,Short,Integer,Long,Float,Double */ public static <E> void main(String[] args) { Integer [] arr = {1,21,3,46,8,67,12,89}; LineTest lt = new LineTest(); int val = lt.<Integer>search(arr,8); System.out.println(val); //java中有类型推断的机制 int val2 = LineTest.search(arr,888); System.out.println(val2); } /** * 定义泛型方法 表示我们这个方法将会用到一个类型E; * 这个类型E到底是什么类型? * 当前不知道,只有在用户调用的时候才能知道 * 那么相应的search方法中的参数类型变成E * 这样就定义了一个泛型方法 * */ public static <E> int search(E[] data,E target){ for(int i = 0; i < data.length; i++) if(data[i].equals(target)) return i; return -1; } }