java二分查找分治法

算法分析

二分查找

package 算法实验;
import java.util.*;

public class t1 {
	 public static void main(String[] args) {
	        int[] a={2,7,9,12,17,20,26,29,31,32,33,43,45};
	        Scanner sc=new Scanner(System.in);
	        System.out.println("请输入要搜索的数:");
	        int x=sc.nextInt();
	        int bin=Binary(a,x,a.length-1);
	        System.out.println("该值的下标为:");
	        System.out.println(bin);
	    }
	    private static int Binary(int[] a, int x, int i) {
		int left=0;
		int right=i-1;
		while (left<=right) {
			int mid=(left+right)/2;
			if(x==a[mid])
				return mid;
			if(x>a[mid])
				return mid+1;
			else
				return mid-1;
		}
		return 0;
	}
}

你可能感兴趣的:(java,算法,算法,java)