1、顺序查找
package com.chazhao; public class Main { public static void main(String[] args) { int[] arr={110,2,23,4,65,6,17,8,9,10,11,21,53,24,35,16}; int result=getIndex(arr, 10); System.out.println(result); } /** * 顺序查找 * @param arr * @param value * @return */ public static int getIndex(int[] arr, int value){ for (int i = 0; i < arr.length; i++) { if (value == arr[i]){ return i; } } return -1; } }
2、有序表查找
前提--有序表
package com.chazhao; public class Main2 { public static void main(String[] args) { int[] arr={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20}; int result=getIndex(arr, 11); System.out.println(result); int result2=getIndex2(arr, 11); System.out.println(result2); } /** * 折半查找 * 思想:取中间的比较对象,如果给定值与比较对象相等,则查找成功;如果给定值小与比较对象, * 则在比较对象左办区查找;否则在右半区查找 * @param arr * @param value * @return */ public static int getIndex(int[] arr, int value){ int left=0, right=arr.length-1; int middle; while (left <= right){ middle=(left+right)/2; int tmp=arr[middle]; if (tmp == value){ return middle; }else if (tmp < value){ left=middle+1; }else if(tmp > value){ right=middle-1; } } return -1; } /** * 插值查找 *思想:对折半查找的优化,仅去middle的值的方式不同 * * 如果查找一个不存在很大的数据,插值查找会导致数组越界异常 * @param arr * @param value * @return */ public static int getIndex2(int[] arr, int value){ int left=0, right=arr.length-1; int middle; while (left < right){ middle=left+(right-left)*(value-arr[left])/(arr[right]-arr[left]); int tmp=arr[middle]; if (tmp == value){ return middle; }else if (tmp < value){ left=middle+1; }else if(tmp > value){ right=middle-1; } } return -1; } }