Blog

It's a Wonderful Life

用java实现二分查找

2017-04-27 12:58 Posted in Learn with Java , algorithm

递归版:

package com.leo.util;

public final class BinarySearch_Recursive
{
    public static void search_begin(int[] haystack, int needle, int begin, int end)
    {
        int mid = Math.round((begin + end) / 2);
        
        if (begin <= end)
        {
            if (haystack[mid] > needle)
                search_begin(haystack, needle, begin, mid - 1);
            else if (haystack[mid] < needle)
                search_begin(haystack, needle, mid + 1, end);
            else if (haystack[mid] == needle)
                System.out.println("Needle found in this haystack at index of " + mid);
        }
        else
        {
           System.out.println("You can never find needle in this haystack");
        }
    }
}

循环版:

package com.leo.util;

public final class BinarySearch_Circular
{
    public static void search_begin(int[] haystack, int needle)
    {
        int begin = 0;
        int end = haystack.length - 1;
        String hint = "You can never find needle in this haystack";
        
        while (begin <= end)
        {
            int mid = Math.round((begin + end) / 2);
            if (haystack[mid] > needle)
                end = mid - 1;
            else if (haystack[mid] < needle)
                begin = mid + 1;
            else
            {
                hint = "Needle found in this haystack at index of " + mid;
                System.out.println(hint);
                return;
            }
        }
        
        System.out.println(hint);
    }
}