线性查找又称顺序查找,是一种最简单的查找方法,它的基本思想是从第一个记录开始,逐个比较记录的关键字,直到和给定的K值相等,则查找成功;若比较结果与文件中n个记录的关键字都不等,则查找失败。
举个栗子🌰:
给定一个整型数组,数组中的元素依次为1、 3、 5、 6、 7、 8,查找数组中是否包含6这个数字,如果包含则返回6在数组中的索引,不包含返回-1。
public class LinearSearch {
// 将构造函数声明成私有的防止用户创建LinearSearch类的对象
private LinearSearch() {}
public static int search(int[] data, int target) {
for (int i = 0, len = data.length; i < len; i++)
if (data[i] == target) return i;
return -1;
}
public static void main(String[] args) {
int[] data = {1, 3, 5, 6, 7, 8};
int res = LinearSearch.search(data, 6);
System.out.println(res); // 3
}
}
class LinearSearch {
static search (data, target) {
for (let i = 0, len = data.length; i < len; i++)
if (data[i] === target) return i
return -1
}
}
const target = 6
const arr = [1, 3, 5, 6, 7, 8]
const res = LinearSearch.search(arr, target)
console.log(res) // 3
扩展:
如果数组中的元素是对象呢,这里我们稍作修改,让方法可以查找对象类型。
public class LinearSearch {
// 将构造函数声明成私有的防止用户创建LinearSearch类的对象
private LinearSearch() {}
public static <T> int search(T[] data, T target) {
for (int i = 0, len = data.length; i < len; i++)
// data和target都是类对象,所以要用equals来判断不能用==,如果用==判断就是引用是否相等
if (data[i].equals(target)) return i;
return -1;
}
public static void main(String[] args) {
// 这里需要注意search方法是一个泛型方法,接收的参数需要是一个类对象而不能是一个基本数据类型
Integer[] data = {1, 3, 5, 6, 7, 8};
int res = LinearSearch.<Integer>search(data,6);
System.out.println(res); // 3
Student[] students = {new Student("Alice"),
new Student("Xiaomi"),
new Student("Kites")};
Student xiaomi = new Student("Xiaomi");
int res3 = LinearSearch.search(students, xiaomi);
System.out.println(res3); // 1
}
}
class LinearSearch {
static search (data, target) {
for (let i = 0, len = data.length; i < len; i++)
if (this.isEqual(data[i], target)) return i
return -1
}
static isEqual(item, target) {
if (item === target) return true
if (typeof item != typeof target) return false
if ((typeof item || typeof target) == 'function') return false
if (JSON.stringify(item) === JSON.stringify(target)) return true
return false
}
}
const target = {name: 'Xiaomi'}
const arr = [{name: 'Alice'}, {name: 'Xiaomi'}, {name: 'Kites'}]
const res = LinearSearch.search(arr, target)
console.log(res) // 3