Home > Java > javaTutorial > body text

Detailed explanation of examples of binary search and binary search in java algorithm

黄舟
Release: 2017-05-21 10:21:15
Original
1899 people have browsed it

This article mainly introduces the java algorithmBinary search and half search related information, friends in need can refer to the following

java algorithm binary search and half search

Half search: First array is sorted

Example code:

package com.hao.myrxjava;

/**
 * 折半查找 :首先数组是已经排好序的
 *
 * @author zhanghaohao
 * @date 2017/5/15
 */

public class Halfpision {

  /**
   * 循环实现
   *
   * @param array 排好序的数组
   * @param value 查找的值
   * @return value在array的位置
   */
  public static int halfpision(int value, int[] array) {
    if (array == null || array.length == 0)
      throw new NullPointerException("array is null");
    int low = 0;
    int high = array.length - 1;
    int mid = (low+high)/2;
    while (array[mid] != value) {
      if (array[mid] > value)
        high = mid - 1;
      else
        low = mid + 1;
      if (low > high)
        return -1;
      mid = (low+high)/2;
      if (array[mid] == value)
        return mid;
    }
    return mid;
  }

  /**
   * 递归实现
   *
   * @param array 排好序的数组
   * @param value 查找的值
   * @param low 查找的起始位置
   * @param high 查找的末尾位置
   * @return value在array的位置
   */
  public static int halfpision(int value, int[] array, int low, int high) {
    if (low > high)
      return -1;
    int mid = (low + high) / 2;
    if (array[mid] == value)
      return mid;
    else if (array[mid] > value)
      return halfpision(value, array, low, mid - 1);
    else if (array[mid] < value)
      return halfpision(value, array, mid+1, high);
    return -1;
  }
}
Copy after login

The above is the detailed content of Detailed explanation of examples of binary search and binary search in java algorithm. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!