二分法查找

package java常用算法;
import java.util.*;

public class 二分查找法 {
    
    public static void main(String[] args) {
        int arr[] = {1,4,5,7,9};
        System.out.println("请输入要查找的数:");
        int tmp = new Scanner(System.in).nextInt();
        System.out.print("查找到的位置在:"+binarySearch2(arr,tmp));
    }
    
    /**
     * 二分法(循环方式)*/
    public static int binarySearch(int a[],int number){
        int head = 0;
        int end = a.length -1;
        int mid = (head+end)/2;
        
        while(head <= end){
            
            if (number == a[mid]){
                return mid;
            }
            else if (number > a[mid]){
                head++;
                mid = (head+end)/2;
            }
            else if (number < a[mid]){
                end--;
                mid = (head+end)/2;
            }
        }
        return -1;
    }
    
    /**
     * 二分法(递归方式)*/
    public static int binarySearch2(int a[],int number){
        return recusion(a,0,a.length-1,number);
    }
    
    public static int recusion(int a[],int head,int end,int number){
        int mid = (head + end)/2;
        if (head > end)
            return -1;
        if (a[mid] > number){
            return recusion(a,head+1,end,number);
        }
        if (a[mid] < number){
            return recusion(a,head,end-1,number);
        }
        else
            return mid;
    }
    
}

你可能感兴趣的:(二分法查找)