一 顺序查找
1.1 分析
顺序查找又称线性查找,基本思想是从线性表的一段开始,逐个检查关键字是否满足给定的条件;若查找到莫个元素的关键字满足给定的条件,则查找成功;返回该元素在线性表中的位置,若已经查找到表的另一端,但还是没有查找到符合给定条件的元素,则返回查找失败的信息;
1.2 实现
package com.thread.lookup;
import java.util.Scanner;
/**
* @description:顺序查找
* @author: Sw_Ljb
* @PACKAGE_NAME:com.thread.lookup
* @time: 2022/8/19 下午7:29
* @version: 1.0
*/
public class SequentialSearch {
public static void main(String[] args) {
Integer[] array = {1,2,3,4,5,7,8};
Scanner scanner = new Scanner(System.in);
//自动的拆箱封箱
Integer elem = scanner.nextInt();
int index = findElemForList(array,elem);
if (index!=0){
System.out.println("当前查询的元素在数组的第"+index+"个位置");
}
else {
System.out.println("当前查询的元素不在数组中");
}
}
/**
* 顺序查找方法
* @param array:数组
* @param elem:元素
* @return
*/
private static int findElemForList(Integer[] array, Integer elem) {
for (int i = 0; i < array.length; i++) {
if (array[i].equals(elem)){
return i+1;
}
}
return 0;
}
}
总结:顺序查找的缺点是当n较大时,平均查找长度较大,效率低;优点是对数据元素存储没有要求,顺序存储与链式存储都可以;对表中记录的有序性也没有要求,无论记录是否按关键字游戏,均可以使用;同时还需要注意,对线性的链表只能进行顺序查找
二 二分查找(折半查找)
2.1 分析
折半查找的基本思想:首先将给定值key与表中中间位置元素比较,若相等,则查找成功,返回该元素的存储位置;若不等,则所需查找的元素只能在中间元素以外的前半部分或后半部分。
2.2 实现
package com.thread.lookup;
import java.util.Scanner;
/**
* @description:顺序查找
* @author: Sw_Ljb
* @PACKAGE_NAME:com.thread.lookup
* @time: 2022/8/19 下午7:29
* @version: 1.0
*/
public class change2Search {
public static void main(String[] args) {
Integer[] array = {1,2,3,4,5,7,8};
Scanner scanner = new Scanner(System.in);
//自动的拆箱封箱
Integer elem = scanner.nextInt();
int index = findElemForList(array,elem);
if (index!=0){
System.out.println("当前查询的元素在数组的第"+index+"个位置");
}
else {
System.out.println("当前查询的元素不在数组中");
}
}
/**
* 二分查找
* @param array:数组
* @param elem:原属
* @return
*/
private static int findElemForList(Integer[] array, Integer elem) {
Integer low =0;
Integer high =array.length-1;
Integer mid;
while (low<=high){
mid = (low+high)/2;
if (array[mid].equals(elem)){
return mid+1;
}
else if (array[mid]>elem){
high = mid -1;
}
else {
low =mid+1;
}
}
return 0;
}
}
总结:因为折半查询需要方便的定位查找区域,所以他要求线性表必须具有随机存取的特性。因此该查找法仅适用于顺序存储结构,不适合于链式存储结构,且要求与书按关键字有序排列