二分查找的实现

The binary search algorithm is used to search an element in the sorted array. It’s faster than linear search and improves perfomance from O(n) to O(logN) for searching an element in the array. In order to perform the binary search, you need a sorted array, so you can either ask the user to enter array in sorted order or you should sort the array before perfoming the binary search. In this article, we will write a Java program which will take input form the user, both array and the number to be serached and then perform a binary search to find that number in given arry. We will not use the Collenctions.binarySearch()method instead we will write our own methodperformBinarySearch(int[] inputArray, int targetNum).

In order to implement binary search, you must first know how how binary search works? if you don not know the algorithm you cannot code it. So, let us first revise the binary search algorithm itself.

How Binary Search Algorithm works

if you remember something about searching algorithms form you data structure and algorithm calsses in college you might know that binary search works on the principle of divede and conquer. In this techique, a solution is found by dividing the inputArray on some rules.

In binary search algorithm, you first find the middle element of the array and compare that with the number you are searching. If it is equal then you return true or index of that number and you binary search is complete but if it does not match then you divide the array in two parts based upon whether the middle element is greater that or less than the key value, which you are searching.

if the key is greater than middle element than search value in the second half of array because the array is sorted in increasing order. Similarily, if the key is lower than middle element it means it is in the first part of the array.

How to implement Binary Search in Java without Recursion

    import java.util.Scanner;
    public class BinarySearch{
        public static void main(String[] args){
            Scanner commandReader = new Scanner(System.in);
            System.out.println("Enter total number of elements : ");
            int length = commandReader.nextInt();

            System.out.printf("Enter %d integers %n", length);
            for(int i = 0 ; i < length; i++){
                inputArray[i] = commandReader.nexInt();
            }
            System.out.println("Please enter number to be searched in array (sorted order)");
            int key = commandReader.nexInt();
            int index = performBinarySearch(inputArray, key);
            if(index = -1) System.out.printf("Sorry, %d is not found in array %n", key);
            else System.out.printf("%d is found in array at index %d %n", key, index);
            commandReader.close();
        }
        public static int performBinarySearch(int[] inputArray, int target){
            int low = 0;
            int high = inputArray.length - 1;
            while(low <= high){
                int middle = (low + high) / 2;
                if(target == middle) return middle;
                else if (target < middle) high = middle - 1;
                else low = middle + 1;
            }
            return -1;
        }
    }

This is an iterative solution of the binary search problem. The time complexity of binary search is in order of O(logN) if you get the sorted input. If you have to sort the input then you need to add that time on the total run time of the algorithm as well.

How to implement binary search suing recursion.

In order to implement a recursive solution, you need a base case because without a base case your program will never terminate and it will eventually die by throwing StackOverFlowError. In the case of recursive binary search implementation, we calculate middle position by taking start and end position and check if the target element is equal to the middle element or not.

So, in each iteration, the value of start and end position changes. At first, start = 0 and end = length - 1 but then depending the value of target element we move the pointer to first or second half of array. This gives you the base case. since the array is getting smaller and smaller in every iteration at one point it will limit to just one element and after that end will be less than the start. At this point, you can stop the binary search because now you can not divide the array further, which means element does not exist in the array. Our solution return -1 at this point of time.

Here is our complete Java solution to implement a recursive binary search. I have a public method recursiveBinarySearch(int[] inputArray, int start, int end, int target) Now the recursive logic is very simple, we calculate middle index by using start and end paratmeter passed to this method, which 0 and length - 1 at the start. After that, we retrieve middle element and compare it with the key or target. If it is equal then we return the index otherwise, we repeat the binary search in the first half or second half of array depending upon whether the key is smaller than the middle element or larger than the key.

    /**
        method which implement recursive binary search algorithm 
      * @param inputArray*
      * @param start 
      * @param end 
      * @param target 
      * @return index of target element or -1 if not found */

    public static int recursiveBinarySearch(int[] inputArray, int start, int end, int target){
        if(start > end) return -1;
        int middle = (start + end) / 2;
        if(target == inputArray[middle]) return middle;
        else if(target < imputArray[middle]) return recursiveBinarySearch(inputArray, start, middle - 1, target);
        else return recursiveBinarySearch(inputArray, middle + 1, end, target);
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值