用最小的内存和二分法查找数组中是否存在这个数

时间:2022-01-21 22:11:24
package Test;

public class Test {
	
//用最小的内存查找数组中是否存在这个数
	public static void main(String[] args) {
		
		int [] arr = {12,2,3,4,5,6,7,8,90,76,43};
		byte[] byt = new byte[100];
		
		for (int i = 0; i < arr.length; i++) {
			byt[arr[i]] = 1;
		}
		
		int n  = 13;
		
		if(byt[n] == 1) {
			System.out.println("存在");
			
		}else {
			
			System.out.println("不存在");
			
		}
		
		
		System.out.println("==========================");
		Test  t = new Test();
		t.paixu(arr, 29);
		
	}
	
	//用二分法查找这个数组中是否存在这个数
	public int paixu(int[] arr,int x) {
		
		System.out.println(arr);
		int min = 0;
		int max = arr.length -1;
		while(min<=max) {
			int middle = (min + max)/2;
			
			if(x == arr[middle]) {
				return middle;//返回该下标
			}else if(x < arr[middle]) {
				max = middle-1;
			}else {
				max = middle+1;
			}
			
			
		}
		return -1;
	}
	
}