java數組和集合的元素查找類似,下面以集合為例。
數組集合元素查找分為兩類:
- 基本查找:
- 二分折半查找:
基本查找:
兩種方式都是for循環來判斷,一種通過索引值來判斷,一種通過數組索引判斷。
索引的方式:
1 public class BaseSearch { 2
3 private static int searchMode02(int[] arr, int mum) { 4 int index=-1; 5 for (int i = 0; i < arr.length; i++) { 6 if (arr[i]==mum) { 7 //在數組中
8 index=i; 9 break; 10 } 11 } 12 //不在數組中
13 return index; 14 } 15
16 public static void main(String[] args) { 17 int[] arr = new int[] {1,2,3,4,5,6,7,8}; 18 int result=searchMode02(arr, 10); 19 System.out.println(result !=-1 ? "元素在數組中":"元素不在數組中"); 20 //元素不在數組中
21 } 22
23 }
索引值判斷的方式:
public class BaseSearch { private static boolean searchMode01(int[] arr, int mum) { for (int i = 0; i < arr.length; i++) { if (arr[i]==mum) { //在數組中
return true; } } //不在數組中
return false; } public static void main(String[] args) { int[] arr = new int[] {1,2,3,4,5,6,7,8}; System.out.println(searchMode01(arr, 10)); //結果false
} }
二分折半查找:
步驟:
1、定義最小索引和最大索引
2、計算中間索引
3、拿中間索引對應的數值和需要查找的數進行比較
數值= 查找的數 返回中間索引
數值 > 查找的數 在左邊找
數值 查找的數 在右邊找
4、重復第二部
5、如果最小的數的值比最大值還要大,那么說明沒有找到返回-1
6、二分查找的數組或者集合必須是有序的
1 /**
2 * 3 * @author liqh 4 * @version 創建時間:2019年4月16日 上午9:12:56 5 * @ClassName 類名稱 6 * @Description 二分查找實現 7
8 public class binarySearch { 9 /** 10 * @Title: main 11 * @Description:二分查找數組中的元素 12 * @param
13 * @return void 返回類型 14 * @throws
15 */
16 public static int findArrValue(int[] arr,int mum) { 17 //定義數組最小元素索引
18 int min=0; 19 //定義數組最大元素索引
20 int max=arr.length-1; 21 //定義數組中間元素索引
22 int mid = (min+max)/2; 23 //判斷中間值是否等於輸入的數
24 while (arr[mid]!=mum) { 25 //判斷中間索引值是否小於mum
26 if (arr[mid]<mum) { 27 //mum比中間值大,在右邊,所以最小索引min需要中間值mid+1
28 min=mid+1; 29 }else if(arr[mid]>mum) { 30 //mum比中間值小,在左邊,所以最大索引值max需要中間索引值mid+1
31 max=mid-1; 32 } 33 //如果一直遞增的最小索引大於一直遞減的最大縮影,那么就是沒有找到
34 if (min>max) { 35 return -1; 36 } 37 //每次計算完之后,min和max都發生改變,中間索引值需要重新計算
38 mid = (min+max)/2; 39
40 } 41 return mid; 42
43 } 44
45 public static void main(String[] args) { 46 int[] arr = new int[] {11,22,33,44,55,66,77,88}; 47 //返回0,表示在數組中,-1表示不再數組中
48 System.out.println(findArrValue(arr, 11)); 49 //結果 0 在數組中
50 } 51
52 }
如果寫的有什么問題,歡迎在下方評論指出來!