1、线性查找法
根据下标值依次挨个查找(顺序查找),找到了就返回
代码实现:
package com.search.find; public class LineFind { public static void main(String[] args) { int[] arr = {1, 3, 6, 4, 44, 11}; int index = find(arr, 11); if (index == -1) { System.out.println("没有找到"); } else { System.out.println("下标为:" + index); } } public static int find(int[] arr, int target) { for (int i = 0; i < arr.length; i++) { if (arr[i] == target) { return i; } } return -1; } }
2、二分查找法
二分查找法的前提是,查找的数据是有序的。
代码实现:
package com.search.find; import java.util.*; public class BinaryFind { public static void main(String[] args) { //测试simpleFind int[] arr = {1, 3, 4, 5, 7, 9, 15}; System.out.println("4下标是:" + simpleFind(arr, 0, arr.length - 1, 4)); System.out.println("****************************"); int[] multiArr = {1, 5, 7, 12, 12, 12, 12, 54}; System.out.println("12下标是:" + multiFind(multiArr, 0, multiArr.length - 1, 12)); } public static int simpleFind(int[] arr, int left, int right, int target) {//查找的数值是唯一的 int mid = (left + right) / 2;//二分中间值的下标 int midVal = arr[mid];//二分中间值 if (left > right) {//没有找到目标值 return -1; } if (midVal > target) { return simpleFind(arr, left, mid - 1, target); } else if (midVal < target) { return simpleFind(arr, mid + 1, right, target); } else { return mid; } } public static List<Integer> multiFind(int[] arr, int left, int right, int target) {//查找的数组是不是唯一的 int mid = (left + right) / 2;//二分中间值的下标 int midVal = arr[mid];//二分中间值 if (left > right) { return null; } if (midVal > target) { return multiFind(arr, left, mid - 1, target); } else if (midVal < target) { return multiFind(arr, mid + 1, right, target); } else { List<Integer> list = new ArrayList<>(); mid = mid - 1; while (arr[mid] == target && mid >= 0) { list.add(mid); mid = mid - 1; } mid = mid + 1; while (arr[mid] == target && mid < arr.length) { list.add(mid); mid = mid + 1; } return list; } } } 输出结果打印: 4下标是:2 **************************** 12下标是:[3, 4, 5, 6]