常见的查找算法
-
线性查找:
package search; /**线性查找 * @author Administrator *顺序查找数列中是否包含该元素,如果找到就提前结束并返回所在的位置。 */ public class SeqSearch { public static void main(String[] args) { int arr[]= {1,9,11,-1,34,89}; System.out.println(seqSearch(arr, -1)); } public static int seqSearch(int[] arr,int value) { for (int i = 0; i < arr.length; i++) { if(arr[i]==value) { return i; } } return -1; } }
-
二分查找:
package search; /**二分查找 * @author Administrator *二分查找首先需要确定数组的中值,然后让目标值与中值比较,如果目标值大就在右边递归查找, *如果目标值小就在左边递归查找 */ public class BinarySearch { public static void main(String[] args) { int arr[]= {1,8,10,89,1000,1234}; System.out.println(binarySearch(arr, 0, arr.length-1, 1000)); } public static int binarySearch(int[] arr,int left,int right,int findVal) { if(left<=right) { int mid=(left+right)/2; int midVal=arr[mid]; if(findVal>midVal) { return binarySearch(arr, mid+1, right, findVal); }else if(findVal<midVal){ return binarySearch(arr, left, mid-1, findVal); }else { return mid; } } return -1; } }
-
插值查找:
package search; /** 插值查找 * @author Administrator *插值查找类似于二分查找,不同的是插值查找每次从自适应mid处开始查找 *将折半查找求mid的公式变为:mid=low+(key-a[low])/(a[high]-a[low])*(high-low); */ public class InsertValueSearch { public static void main(String[] args) { int arr[]= {1,8,10,89,1000,1234,1456,1892}; System.out.println(insertValueSearch(arr, 0, arr.length-1, 1892)); } public static int insertValueSearch(int[] arr,int left,int right,int findVal) { if (left>right || findVal<arr[0] || findVal>arr[arr.length-1]) { return -1; } int mid=left+(right-left)*(findVal-arr[left])/(arr[right]-arr[left]); int midVal=arr[mid]; if (findVal>midVal) { return insertValueSearch(arr, mid+1, right, findVal); }else if (findVal<midVal) { return insertValueSearch(arr, left, mid-1, findVal); }else { return mid; } } }