package com.algorithm;
import java.util.ArrayList;
import java.util.List;
/**
* 类功能描述:
*
* @author Barry
* @version 1.0.0
* @auther Create by Barry
* @date Create on 2018/3/12.
* @history
*/
public class BinarySearch {
public static int binarySearch(List<Integer> list, int k){
if(list == null || list.isEmpty()){
new RuntimeException("请传入正确的列表");
}
int min = 0;
int max = list.size()-1;
int middle;
while(min <= max){
middle = (min+max)/2;
int data = list.get(middle);
if(data == k ){
return middle;
}
if(data < k){
min = middle+1;
}
if(data > k){
max = middle-1;
}
}
return -1;
}
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
list.add(-200);
list.add(-30);
list.add(-10);
list.add(3);
list.add(5);
list.add(8);
list.add(10);
list.add(100);
list.add(1000);
System.out.println(BinarySearch.binarySearch(list, 3));
}
}