【java学习笔记18】数组排序算法之一般查找(如数组中有该元素返回下标,没有返回-1)

题目如题:

用一般的for循环遍历数组,如果有要查询的元素,返回对应的下标,如果没有该元素,返回-1;

 

package ArraySorted;

public class ArrayTest04 {

    public static void main(String[] args) {

        // 基本查找

        int[] array = {4,7,90,40,33,18,75};

        int n = index(array,4);
        System.out.println(n);
    }

    private static int index(int[] array,int ele){
        for (int i = 0; i < array.length; i++) {
            if (array[i] == ele){
                return i;
            }
        }
        return -1;
    }
}

 

posted @ 2021-01-05 20:45  愚人李愚  阅读(371)  评论(0)    收藏  举报