这里引入百度百科的解释:
package com.lingo.search; /** * 线性查找/顺序查找 最基本最基础的循环查找 也是效率最低的查找方式 */ public class SequentialSearch { public static void main(String[] args) { int[] arr = {1, 5, 8, 66, 55, 1, 2, 33, 555, 156, 498, 512, 223, 156}; int result = sequentialSearch(arr, 555); System.out.println(result); } public static int sequentialSearch(int[] arr, int value) { for (int i = 0; i < arr.length; i++) { if (value == arr[i]) { return i; } } return -1; } }
输出结果:
8
package com.lingo.search; public class BinarySearchT { private static int search(int[] arr, int left, int right, int value) { //递归中止条件 if (left > right) { return -1; } int mid = left + (right - left) / 2; if (value < arr[mid]) { return search(arr, left, mid, value); } else if (value > arr[mid]) { return search(arr, mid + 1, right, value); } else { return mid; } } public static int search(int[] arr, int value) { return search(arr, 0, arr.length - 1, value); } public static void main(String[] args) { int[] arr = {1, 5, 8, 15, 55, 212, 333, 411, 555}; int result = search(arr, 333); System.out.println(result); } }
输出结果:
6
package com.lingo.search; public class InsertionSearchT { private static int search(int[] arr, int left, int right, int value) { //递归中止条件 if (left > right) { return -1; } //这里如果不加判断会导致空指针异常 if (value > arr[arr.length - 1] || value < arr[0]) { return -1; } int mid = left + (right - left) * (value - arr[left]) / (arr[right] - arr[left]); if (value < arr[mid]) { return search(arr, left, mid, value); } else if (value > arr[mid]) { return search(arr, mid + 1, right, value); } else { return mid; } } public static int search(int[] arr, int value) { return search(arr, 0, arr.length - 1, value); } public static void main(String[] args) { int[] arr = {1, 5, 8, 15, 55, 212, 333, 411, 555}; int result = search(arr, 212); System.out.println(result); } }
输出结果:
5
package com.lingo.search; import java.util.Arrays; public class FibonaciiSearchT { private static int maxSize = 20; public static int search(int[] arr, int value) { if (arr[0] > value || arr[arr.length - 1] < value) { return -1; } int[] f = getFibonaciiArr(); int low = 0; int k = 0;//斐波那契数列下标 int high = arr.length - 1; while (high > f[k]) { k++; } int[] copyArr = Arrays.copyOf(arr, f[k]); for (int i = high + 1; i < copyArr.length; i++) { copyArr[i] = arr[high]; } while (low <= high) { int mid = low + f[k - 1] - 1;//下标0开始 if (value > copyArr[mid]) { //f[k] = f[k-1]+f[k-2] low = mid + 1; k -= 2; } else if (value < copyArr[mid]) { high = mid - 1; k -= 1; } else { if (mid <= high) { return mid; } else { return high; } } } return -1; } private static int[] getFibonaciiArr() { int[] f = new int[maxSize]; f[0] = 1; f[1] = 1; for (int i = 2; i < maxSize - 1; i++) { f[i] = f[i - 1] + f[i - 2]; } return f; } public static void main(String[] args) { int[] arr = {1, 5, 8, 15, 55, 212, 333, 411, 555}; int result = search(arr, 212); System.out.println(result); } }
输出结果:
5