本文共 1127 字,大约阅读时间需要 3 分钟。
二分查找算法就是不断将数组进行对半分割,每次拿中间元素和goal进行比较。
代码如下:import java.util.Arrays;import java.util.Scanner;// This is Binary Choppublic class Thinkgamer { static int a[] = {0,1,2,3,4,5,6,7,8,9,10},num,loc; public static void binaryChop(int low,int high){ int left = low,right = high; int mid = (low+high)/2; if((high-low)==1){ if(num==a[low]) loc = low; else if(num==a[high]) loc =high; else loc =-1; } else{ if(numa[mid]) binaryChop(mid+1,right); else if(num==a[mid]) loc = mid; else loc =-1; } } public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("请输入要查找的数:"); Scanner in = new Scanner(System.in); num = in.nextInt(); //手动输入要查找的数 binaryChop(0,10); //二分查找 if(loc!=-1) System.out.println(num + "在该数组中,且位置是 "+ loc); else System.out.println(num+ "不在该数组中!!!"); }}
转载地址:http://ssuio.baihongyu.com/