线性查找
package lesson.l7_array;/*** Illustration** @author DengQing* @version 1.0* @datetime 2022/6/23 14:19* @function 线性查找*/
public class LineSearch {public static void main(String[] args) {String[]str={"AA","BB","CC"};boolean flag=false;String dest="BB";for (int i = 0; i < str.length; i++) {if (dest.equals(str[i])){System.out.println("已找到元素"+dest+",位置为"+i);flag=true;break;}}if (!flag){System.out.println("没有找到元素"+dest);}}
}
线性查找-方式2
public class LineSearch2 {public static void main(String[] args) {String[]str={"AA","BB","CC"};String dest="DD";int i;for (i = 0; i < str.length; i++) {if (dest.equals(str[i])){System.out.println("已找到元素"+dest+",位置为"+i);break;}}if (i==str.length){System.out.println("没有找到元素"+dest);}}
}
二分查找
注意点:二分查找是与中间值做比较
package lesson.l7_array;/*** Illustration** @author DengQing* @version 1.0* @datetime 2022/6/23 14:43* @function 二分查找:数组必须有序*/public class BinarySearch {public static void main(String[] args) {int[] arr = {1, 2, 3, 4, 5, 10, 20, 100};int dest = 10;int left = 0;int right = arr.length;boolean flag = false;while (left <= right) {int middleIndex = (left + right) / 2;int middle = arr[middleIndex];if (dest == middle) {System.out.println("已找到" + dest);flag = true;break;
// 往前找} else if (dest < middle) {right = middleIndex - 1;
// 往后找} else {left = middleIndex + 1;}}if (!flag) {System.out.println("没有找到" + dest);}}
}