线性查找
package com.dai.search; public class SeqSearch { public static void main(String[] args) { // TODO Auto-generated method stub int[] arr = {1, 9, 11, -1, 34, 89};//无序的数组 int index = seqSearch(arr, 11); if(index==-1) { System.out.println("没找到"); }else { System.out.println("找到,下标为" + index); } } //线性查找,找到一个,就返回下标 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 com.dai.search; import java.util.List; import java.util.ArrayList; import java.util.Arrays; public class BinarySearch { public static void main(String[] args) { int arr[] = {1,8,10,1000,1000,1000,1234};//二分查找的数组是有序的 ArrayList resIndexList =binarySearch2(arr, 0, arr.length-1, 1000); System.out.println("resIndexList=" + resIndexList); } //二分查找算法 /* * arr:数组 * left: 左索引 * right:右索引 * findVal:找到的下标 * */ public static int binarySearch(int[] arr, int left, int right, int findVal) { //当left>right,说明递归整个数组都没有找到,直接return if(left>right) { return -1; } 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; } } //如何找到所有的下标? //在找到Mid时,不要马上返回,向Mid左边和右边扫描,将满足条件的下标加入集合 public static ArrayList binarySearch2(int[] arr, int left, int right, int findVal) { //当left>right,说明递归整个数组都没有找到,直接return if(left>right){ return new ArrayList<Integer>(); } int mid = (left+right)/2; int midVal = arr[mid]; if(findVal > midVal) { return binarySearch2(arr, mid+1, right, findVal); }else if(findVal < midVal){ return binarySearch2(arr, left, mid-1, findVal); } else { ArrayList<Integer> resIndexList = new ArrayList<Integer>(); int temp = mid-1; while(true) { if(temp<0 || arr[temp] != findVal) { break; }else { resIndexList.add(temp); temp -= 1; } } resIndexList.add(mid); temp = mid+1; while(true) { if(temp>arr.length-1 || arr[temp] != findVal) { break; }else { resIndexList.add(temp); temp += 1; } } return resIndexList; } } }