java算法:二分查找

二分查找也称折半查找(Binary Search),它是一种效率较高的查找方法。但是,折半查找要求线性表必须采用顺序存储结构,而且表中元素按关键字有序排列。


package Sort;
import org.junit.Test;

/**
*类描述:对一个数组进行二分查找
*@author: 张宇
*@date: 日期: 2018年8月20日 时间: 上午10:07:19
*@version 1.0
 */
public class BinarySearch {
	@Test
	public  void fun() {
        int arr[]={1,3,4,5,6,7,8,9,10};
        System.out.println(binarySearch(arr, 4));
	}
	//二分查找,如果找到就返回1,如果没有找到就返回-1
    public  int binarySearch(int[] arr,int key){
    	int start=0;
    	int end=arr.length-1;
    	while(start<=end){
    		int mid=(start+end)/2;
    		if(key>arr[mid]){
    			start=mid+1;
    		}else if(key<arr[mid]){
				end=mid-1;
			}else{
				return 1;
			}
    	}
    	return -1;
    }	
}

猜你喜欢

转载自blog.csdn.net/zy345293721/article/details/81874495
今日推荐