for循环遍历查找:
public class Main{ public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int[] arr = {3, 78, 9, 66, 45}; int index = getIndexByEle(arr,n); System.out.println(index); } private static int getIndexByEle(int[] arr, int n) { //遍历数组 for (int i = 0; i < arr.length; i++) { if (arr[i] == n) { return i; } } return -1; } }
二分查找:
public class Main{ public static void main(String[] args) { int[] arr={10,20,30,40,50,60,70,80,90}; int index= getIndexByEle( arr, 90); System.out.println(index); } public static int getIndexByEle(int[] arr,int n){ int minIndex=0; int maxIndex=arr.length-1; int centerIndex=(minIndex+maxIndex)/2; while (minIndex<=maxIndex){ //第一种情况,如果找见的元素正好是中间的元素 if(n==arr[centerIndex]){ return centerIndex; }else if (n>arr[centerIndex]){ //第二种情况,如果所得元素大于中间元素,那么将minIdex向后移 minIndex=centerIndex+1; }else if (n<arr[centerIndex]){ //第三种情况,如果所得元素小于中间元素,那么maxIndex向前移 maxIndex=centerIndex-1; } centerIndex=(minIndex+maxIndex)/2; } return -1;//如果没有的话返回-1 } }