Java笔记--数组练习,查找元素索引

练习

要求:根据数组元素,查找出该元素第一次在数组中出现的索引。

​ 方式一:遍历数组挨个去查找

​ 方式二:二分查找

方式一:

package com.excersice;

public class Demo08 {
    public static void main(String[] args) {
        //定义一个数组
        int[] arrays = {1,2,3,4,5,6,7,8,9,12,11,13,14,6};
        //根据该元素查找出该元素在数组中第一次出现的索引
        int index = getIndexByEle(arrays,15);
        System.out.println("该元素第一次在数组中出现的索引是" + index);
    }

    private static int getIndexByEle(int[] array, int ele) {
        //遍历数组去查找
        for (int i = 0; i < array.length; i++) {
            if (ele==array[i]){
                return i;
            }
        }

        return -1;  //如果我们没有找到这个元素,那么就返回-1
    }
}

以下是自己编写的,分析:没有设定返回值类型,这样不方便外部调用,接收定位数据。

package com.excersice;

public class Demo06 {
    /*
    要求:根据数组元素,查找出该元素第一次在数组中出现的索引。

        方式一:遍历数组挨个去查找

        方式二:二分查找
     */
    public void findIndex(int[] arrays1, int a){
        int[] arrays = arrays1;
        int num = a;
        for (int i= 0; i<arrays.length; i++){
            if (arrays[i]==num){
                System.out.println("此元素所在位置是:" + i);
            }else {
                System.out.println("此数组中不包含此元素" + num);
                break;
            }

        }

    }
}

方式二:二分查找

分析思路:二分查找是通过不断的二分,来减少计算步骤,而不是简单一次二分就遍历元素进行比较。所以要用到while循环。首先定义3个变量接收数组的三个位置的数值,分别为:首、尾、中。通过判断将这三个变量动起来,而不是简单定死。如果不事先定义好变量就流动不起来,自然完不成任务。

package com.excersice;

import java.util.Arrays;

public class Demo09 {
    //方式二:二分查找
    public int findIndexEle(int[] arr, int a){
        Arrays.sort(arr);
        //a元素与数组中间元素比对之后会出现三种情况:相等、大于、小于

        int minIndex = 0;
        int maxIndex = arr.length-1;
        int midIndex = (minIndex+maxIndex)/2;
        while (minIndex<=maxIndex){
            if (a==arr[midIndex]){
                return midIndex;
            }else if (a>arr[midIndex]){
                minIndex = midIndex+1;
            }else {
                maxIndex = midIndex-1;
            }
            midIndex = (minIndex+maxIndex)/2;
        }

        return -1;
    }
}

应用:

package com.excersice;

public class Demo09Application {
    public static void main(String[] args) {
        int[] arrays = {1,2,3,4,5,6,7,8,9,11,12,13,14,15,16,34,56,78,76,49,21,92};
        Demo09 demo09 = new Demo09();
        int a = demo09.findIndexEle(arrays,15);
        System.out.println(a);    //13

        int b = demo09.findIndexEle(arrays, 100);
        System.out.println(b);
    }
}

版权声明:本文为Medzy原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。