java数组集合元素的查找

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 }

 如果写的有什么问题,欢迎在下方评论指出来!

原文地址:https://www.cnblogs.com/lqhhome/p/10715088.html