问题描述
提示:线性搜索就是一个个的找
实现
public static <E extends Comparable<E>> int linearSearch(E[] list, E key)方法
难点分析:
提示:这道题很简单~~
泛型的运用
代码:
提示:注意是泛型所以传参数不能是基本类型只能是Integer,String...对象,这里提供一下另外一种思路:list[i].equals(key)这一句也完全可以用list[i].comparaTo(key) == 0;
import java.util.ArrayList;
public class exe19_04 {
public static void main(String[] args) {
String[] List = new String[3];
List[0] = "zhangsan";
List[1] = "lisi";
List[2] = "wangwu";
System.out.println("wangwu's index: " + linearSearch(List, "wangwu"));
Integer[] arr = new Integer[10];
for (int i = 0; i < 10; i++) {
arr[i] = (int) (Math.random() * 10 + 1);
}
System.out.println("8 index: " + linearSearch(arr, 8));
}
public static <E extends Comparable<E>> int linearSearch(E[] list, E key) {
int res = -1;
for (int i = 0; i < list.length; i++) {
if (list[i].equals(key)) {
res = i;
break;
}
}
return res;
}
}