package com.hao.myrxjava;
/**
* 折半查找 :首先数组是已经排好序的
*
* @author zhanghaohao
* @date 2017/5/15
*/
public class HalfDivision {
/**
* 循环实现
*
* @param array 排好序的数组
* @param value 查找的值
* @return value在array的位置
*/
public static int halfDivision(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 halfDivision(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 halfDivision(value, array, low, mid - 1);
else if (array[mid] < value)
return halfDivision(value, array, mid+1, high);
return -1;
}
}
二分查找、折半查找
最新推荐文章于 2022-11-16 18:49:29 发布