首先声明一个概念:查找的基本方法可以分为两大类,即比较式查找法和计算机式。其中比较式查找法有可以分为基于线性表的查找法和基于树的查找法,而计算查找法也称为也称为HASH(哈希)查找法。
查找-是最常见的数据操作之一,数据结构核心运算之一,其重要性不言而喻。顺序查找是人们最熟悉的查找策略,对于小规模的数据,顺序查找是个不错的选择。
1.顺序查找:
核心:从数据的第一个元素开始,依次比较,直到找到目标数据或查找失败。
1.从表中的第一个元素开始,依次与关键字比较。
2.若某个元素匹配关键字,则查找成功。
3.若查找到最后一个元素还未匹配关键字,则查找失败。
2.时间复杂度:
顺序查找平均关键字匹配次数为表长的一半,其时间复杂度为O(n)。
3.顺序查找的评估:
顺序查找的优点是对表无要求,插入数据可在O(1)内完成。缺点是时间复杂度较大,数据规模较大时,效率较低。
解法一:使用基本的返回具体在表中的位置(没有设置监视哨)public class SeqSearch { public static void main(String[] args) { int[] data = {3,45,2,6,4,7,8,23,34,43,17,26,46}; Scanner scanner = new Scanner(System.in); while(true){ int k = scanner.nextInt(); int result = getIndex(data, k); if(result >= 0){ System.out.println("查找的"+k+"在数组中第:"+(result+1)); } else{ System.out.println("查找的"+k+"不在数组中"); } } } public static int getIndex(int[] data, int k){ int i = data.length-1; while(i >= 0 && data[i] != k){ i--; } return i; } }
不返回位置:
public class SeqSearch { public static void main(String[] args) { int[] data = {3,45,2,6,4,7,8,23,34,46,17,26,46}; Scanner scanner = new Scanner(System.in); while(true){ int k = scanner.nextInt(); boolean result = getIndex(data, k); if(result){ System.out.println("查找的"+k+"在数组中"); } else{ System.out.println("查找的"+k+"不在数组中"); } } } public static boolean getIndex(int[] data, int k){ for(int i = data.length-1; i >= 0; i--){ if(data[i] == k){ return true; } } return false; } }
解法二(设置监视哨)
public class SeqSearch2 { public static void main(String[] args) { int[] data = {0,45,2,6,4,7,8,23,34,46,17,26,46}; Scanner scanner = new Scanner(System.in); while(true){ int k = scanner.nextInt(); int result = getIndex(data, k); if(result == 0){ System.out.println("查找的"+k+"不在数组中"); }else{ System.out.println("查找的"+k+"在数组中第:"+result); } } } public static int getIndex(int[] data, int k){ data[0] = k; int i = data.length-1; while(i >= 1 && data[i] != k){ i--; } if(i >= 1){ return i; }else{ return 0; } } }