java binary search_Java BinarySearch

/**

*

*

*

Copyright 1994-2018 JasonInternational

*

All rights reserved.

*

Created on 2018年4月10日 上午9:46:32

*

Created by Jason

*

*

*/

package cn.ucaner.algorithm.search;

/**

* In computer science, binary search, also known as half-interval search or logarithmic search, is a search algorithm that finds the position of a target value within a sorted array. Binary search

* compares the target value to the middle element of the array; if they are unequal, the half in which the target cannot lie is eliminated and the search continues on the remaining half until it is

* successful or the remaining half is empty.

*

* Worst-case performance O(log n)

* Best-case performance O(1)

* Average performance O(log n)

* Worst-case space complexity O(1)

*

* @see Binary Search (Wikipedia)

*

* @author Justin Wetherell

*/

public class BinarySearch {

private static final int SWITCH_TO_BRUTE_FORCE = 200;

private static int[] sorted = null;

// Assuming the array is sorted

public static final int find(int value, int[] array, boolean optimize) {

BinarySearch.sorted = array;

try {

return recursiveFind(value, 0, BinarySearch.sorted.length - 1, optimize);

} finally {

BinarySearch.sorted = null;

}

}

private static int recursiveFind(int value, int start, int end, boolean optimize) {

if (start == end) {

int lastValue = sorted[start]; // start==end

if (value == lastValue)

return start; // start==end

return Integer.MAX_VALUE;

}

final int low = start;

final int high = end + 1; // zero indexed, so add one.

final int middle = low + ((high - low) / 2);

final int middleValue = sorted[middle];

if (value == middleValue)

return middle;

if (value > middleValue) {

if (optimize && (end - middle) <= SWITCH_TO_BRUTE_FORCE)

return linearSearch(value, middle + 1, end);

return recursiveFind(value, middle + 1, end, optimize);

}

if (optimize && (end - middle) <= SWITCH_TO_BRUTE_FORCE)

return linearSearch(value, start, middle - 1);

return recursiveFind(value, start, middle - 1, optimize);

}

private static final int linearSearch(int value, int start, int end) {

for (int i = start; i <= end; i++) {

int iValue = sorted[i];

if (value == iValue)

return i;

}

return Integer.MAX_VALUE;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值