package sort; /** * @Author fyp * @Description * @Date Created at 2018/1/22 9:52 * @Project tio-http-server */ public class FastSort { public static void main(String[] args){ int[] ints = new int[]{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}; int searchIndex = search(ints,15); System.out.println("找到的索引值為:"+searchIndex); } /** * 二分查詢法 * 取中間值,然後比較,大,小,等於,直到比較出結果 * */ private static int search(int[] ints,int value){ int startIndex = 0; int endIndex = ints.length - 1; int middleIndex; while (startIndex <= endIndex){ //取出中間索引值 middleIndex = (startIndex + endIndex) / 2; //如果value就和中間值相等,直接找到了,返回 O(1) if(value==ints[middleIndex]){ return middleIndex; } if(value > ints[middleIndex]){ //值大於中間值,從右邊開始(+1 排除middleIndex的值) startIndex = middleIndex + 1; }else{ //值小於中間值,從左邊開始找(-1排除middleIndex的值) endIndex = middleIndex - 1; } } //如果執行到這裡還沒有返回值,說明陣列裡面沒有 return -1; } }