binarysearch.java

来自「Java 入门书的源码」· Java 代码 · 共 40 行

JAVA
40
字号
//Copyright (c) 1998, Arthur Gittleman
//This example is provided WITHOUT ANY WARRANTY either expressed or implied.

/* Inputs integers in order from smallest to largest on the
 * command line.  Uses a recursive method to implement binary
 * search.
 */

import iopack.*;
public class BinarySearch {
  public static int binarySearch(int [] data, int key, int left, int right) {
    if (left <= right) { 
      int middle = (left + right)/2;       
      if (key == data[middle])
        return middle;
      else if (key < data[middle])
        return binarySearch(data,key,left,middle-1);
      else 
        return binarySearch(data,key,middle+1,right);
    }
    return -1;   
  }
  public static void main(String [] args) {
    int key;       // the search key
    int index;     // the index returned
    char repeat;   // 'Y' to repeat, 'N' to quit
    int [] data = new int[args.length];
    for (int i=0; i < data.length; i++)
      data[i] = Integer.parseInt(args[i]);
    do {
      key = Io.readInt("Enter the search key");
      index = binarySearch(data,key,0,data.length-1);
      if (index == -1)
        System.out.println("Key " + key + " not found");
      else
        System.out.println("Key " + key + " found at index " + index);
      repeat = Io.readChar("Enter 'Y' to repeat, 'N' to quit");
    }while (repeat=='Y' || repeat == 'y');
  }
}       

⌨️ 快捷键说明

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