Java查找数组中的指定元素(顺序查找)

顺序查找数组中的指定元素
给定一个数组,在给定一个元素,找出该元素在数组中的位置(输出的是该元素在数组中的下标)

public static void main(String[] args) {
    
    
        int[] array = {
    
    12, 14, 16, 18, 20, 28};
        System.out.println(find(array,16));
    }

    public static int find(int[] arr, int toFind) {
    
    
        for (int i = 0; i < arr.length; i++) {
    
    
            if (arr[i] == toFind) {
    
    
                return i;
            }
        }
        return -1; // 表示没有找到 }
    }

结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44436675/article/details/112086348