利用折半查找,寻找元素在数组中合适恰当的位置

import java.util.Scanner;

public class zheBan {
	public static void main(String args[]) {
		Scanner input = new Scanner(System.in);
		//折半查找,前提:数组是有序数组
		int[] arr = {-12,2,9,11,18,36,54,98,112,365,420,600};
		System.out.print("原数组:");
		arrPrint(arr);
		
		//动态接收要查找的数字
		System.out.print("输入要查找位置的数:");
		int num = input.nextInt();
		int index = findIndex(arr,num);
		System.out.println("要查找的数("+num+")在数组中恰当的下标是("+index+")");
	}

	// 遍历数组
	public static void arrPrint(int[] arr) {
		System.out.print("{");
		for (int i = 0; i < arr.length; i++) {
			if (i == arr.length - 1) {
				System.out.print(arr[i] + "}\n");
			} else {
				System.out.print(arr[i] + ",");
			}
		}
	}
	
	//查找
	public static int findIndex(int[] arr, int index){
		int min = 0;
		int mid;
		int max = arr.length - 1;
		while(min <= max){
			mid = (min + max) / 2;
			if(index > arr[mid]){
				min = mid + 1;
			}else if(index < arr[mid]){
				max = mid - 1;
			}else{
				return mid;
			}
		}
		return min;
	}
	
}

你可能感兴趣的:(Java基础)