Java教程

Java 实现二分搜索算法的程序

实现二分搜索算法的Java程序

在这个例子中,我们将学习在 Java 中实现二分查找算法。
要理解此示例,您应该了解以下Java 编程主题:
Java while 和 do...while 循环 Java if...else 语句 Java 数组

示例: 实现二分搜索算法的 Java 程序

import java.util.Scanner;
// Binary Search in Java
class Main {
  int binarySearch(int array[], int element, int low, int high) {
    // Repeat until the pointers low and high meet each other
    while (low <= high) {
      // get index of mid element
      int mid = low + (high-low) / 2;
      // if element to be searched is the mid element
      if (array[mid] == element)
        return mid;
      // if element is less than mid element
      // search only the left side of mid
      if (array[mid] < element)
        low = mid + 1;
      // if element is greater than mid element
      // search only the right side of mid
      else
        high = mid-1;
    }
    return -1;
  }
  public static void main(String args[]) {
    // create an object of Main class
    Main obj = new Main();
    // create a sorted array
    int[] array = { 3, 4, 5, 6, 7, 8, 9 };
    int n = array.length;
    // get input from user for element to be searched
    Scanner input = new Scanner(System.in);
    System.out.println("Enter element to be searched:");
    // element to be searched
    int element = input.nextInt();
    input.close();
    // call the binary search method
    // pass arguments: array, element, index of first and last element
    int result = obj.binarySearch(array, element, 0, n-1);
    if (result ==-1)
      System.out.println("Not found");
    else
      System.out.println("Element found at index " + result);
  }
}
输出 1
Enter element to be searched:
6
Element found at index 3
在这里,我们使用了 Java Scanner Class 来获取用户的输入。根据用户的输入,我们使用二进制搜索来检查元素是否存在于数组中。
我们也可以使用递归调用来执行相同的任务。
  int binarySearch(int array[], int element, int low, int high) {
    if (high >= low) {
      int mid = low + (high-low) / 2;
      // check if mid element is searched element
      if (array[mid] == element)
        return mid;
      // Search the left half of mid
      if (array[mid] > element)
        return binarySearch(array, element, low, mid-1);
      // Search the right half of mid
      return binarySearch(array, element, mid + 1, high);
    }
    return -1;
  }
此处,方法 binarySearch() 会调用自身,直到找到元素或 if 条件失败。
如果您想了解有关二分搜索算法的更多信息,请访问二分搜索算法。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4