集册 Java实例教程 使用二进制搜索查找数组中的项。

使用二进制搜索查找数组中的项。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

577
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
使用二进制搜索查找数组中的项。
/*
 from 时 代      J a v a   公   众 号 - nowjava.com 
*/

import java.security.SecureRandom;

import java.util.Arrays;


public class Main {

  public static int binarySearch(int[] data, int key) {

    int low = 0; // low end of the search area

    int high = data.length - 1; // high end of the search area

    int middle = (low + high + 1) / 2; // middle element

    int location = -1; // return value; -1 if not found


    do {

      System.out.print(remainingElements(data, low, high));


      for (int i = 0; i < middle; i++)

        System.out.print("   ");// 来自 nowjava.com - 时代Java

      System.out.println(" * "); // indicate current middle


      // if the element is found at the middle

      if (key == data[middle])

        location = middle; // location is the current middle

      else if (key < data[middle]) // middle element is too high

        high = middle - 1; // eliminate the higher half

      else

        // middle element is too low

        low = middle + 1; // eliminate the lower half


      middle = (low + high + 1) / 2; // recalculate the middle

    } while ((low <= high) && (location == -1));


    return location;

  }


  private static String remainingElements(int[] data, int low, int high) {

    StringBuilder temporary = new StringBuilder();


    // append spaces for alignment

    for (int i = 0; i < low; i++)

      temporary.append("   ");


    // append elements left in array

    for (int i = low; i <= high; i++)

      temporary.append(data[i] + " ");


    return String.format("%s%n", temporary);

  }


  public static void main(String[] args) {

    SecureRandom generator = new SecureRandom();


    int[] data = new int[15]; // create array


    for (int i = 0; i < data.length; i++)

      // populate array

      data[i] = 10 + generator.nextInt(90);


    Arrays.sort(data); // binarySearch requires sorted array

    System.out.printf(
展开阅读全文