package com.LeetCode; /** * 算法:二分搜索法查找一個值,並返回索引值 * https://leetcode.com/problems/search-insert-position/ * */ public class BinSearch { public static void main(String[] args) { int[] a = {1,3,5,6}; int[] b = {1,5,8, 13, 19}; int[] c = {3,5,11,17,21,23,28,30,32,50,64,78,81,95,101}; int result = binSearch2(a, 0); System.out.println("Index is:" + result); } public static int binSearch2(int srcArray[], int key) { int start = 0; int end = srcArray.length -1; int mid = srcArray.length / 2 ; System.out.println("mid="+mid); if (key == srcArray[mid]) { return mid; } while (start <= end) { mid = (end-start)/2+start; System.out.println("Now mid="+mid); if(key<srcArray[0]) { System.out.println("Smaller than all numbers in array. return 0"); return 0; } if(key>srcArray[end]) { System.out.println("Bigger than all numbers in array."); return srcArray.length; } if ((key>srcArray[mid-1]) && (key < srcArray[mid])) { System.out.println("Not in index, return 'mid' value"); return mid; } if (key<srcArray[mid]) { end = mid-1; } else if (key>srcArray[mid]) { start = mid+1; } else { { return mid; } } } System.out.println("Can't find the number in array."); return -1; } }