binarysearch.java

来自「java程序设计 清华出版社 孙燮华老师编写的程序源代码」· Java 代码 · 共 46 行

JAVA
46
字号
 //BinarySearch.java      比较数组元素值的大小
    public class BinarySearch
    {
      public static void main(String args[])
      {
        int i, mid, low, high, midvalue, key;
        boolean flag;
        low=0;
        key=21;
        int a[] = {5, 13, 19, 21, 37, 56, 64, 75, 80, 88, 92};  //声明数组a,并赋初值
        high=a.length-1;
        flag=true;

        while(flag){
          flag=false;
          mid=(low+high)/2;
          midvalue=a[mid];
          if(low==high){
            if(key==midvalue){
              System.out.println("Find the key! The index of the key " + key + " is: " + mid);
            }
            else{
              System.out.println("Can not find the key " + key + " !");
            }
            flag=false;
            break;
          }
          if(key==midvalue){
            System.out.println("Find the key! The index of the key " + key + " is: " + mid);
            flag=false;
            break;
          }
          else if(key<midvalue){
            high=mid-1;
            flag=true;
          }
          else{
            low=mid+1;
            flag=true;
          }
        }
      }
    }
        
    

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?