1. 程式人生 > >Java面試--常見的邊界控制問題

Java面試--常見的邊界控制問題

常見的邊界控制問題

二分查詢

例 【二分查詢】  在有序陣列中查詢元素 k ,返回 k 所在的下標

在陣列 [1,2,10,15,100] 中去尋找 15 ,15 的下標是 3 ;

二分查詢思路:

程式碼實現:BinarySearch.java

package interview.loop;

public class BinarySearch {

  /**
   * Searches element k in a sorted array.
   * @param arr a sorted array
   * @param k the element to search
   * @return index in arr where k is. -1 if not found.
   */
  public int binarySearch(int[] arr, int k) {	//傳入引數陣列
    int a = 0;			//定義陣列下標 a、b
    int b = arr.length;		//陣列下標包含整個陣列
	//二分查詢要保證的條件
    // Loop invariant: [a, b) is a valid range. (a <= b)
    // k may only be within range [a, b).
    while (a < b) {
      int m = a + (b - a) / 2; // m = (a + b) / 2 may overflow! 防止記憶體溢位
      if (k < arr[m]) {		//k 與中間節點 m 做比較,要查詢的資料在 m 的左邊
        b = m;
      } else if (k > arr[m]) {	//要查詢的資料在 m 的右邊
        a = m + 1;
      } else {
        return m;
      }
    }
    return -1;		//查詢不到則返回 -1
  }

  public static void main(String[] args) {	//測試用例
    BinarySearch bs = new BinarySearch();

    System.out.println("Testing normal data");	
    System.out.println(
        bs.binarySearch(new int[]{1, 2, 10, 15, 100}, 15));
    System.out.println(
        bs.binarySearch(new int[]{1, 2, 10, 15, 100}, -2));
    System.out.println(
        bs.binarySearch(new int[]{1, 2, 10, 15, 100}, 101));
    System.out.println(
        bs.binarySearch(new int[]{1, 2, 10, 15, 100}, 13));
    System.out.println("======");

    System.out.println("Testing empty or singleton data.");
    System.out.println(
        bs.binarySearch(new int[]{}, 13));
    System.out.println(
        bs.binarySearch(new int[]{12}, 13));
    System.out.println(
        bs.binarySearch(new int[]{13}, 13));
    System.out.println("======");

    System.out.println("Testing data of size 2.");
    System.out.println(
        bs.binarySearch(new int[]{12, 13}, 13));
    System.out.println(
        bs.binarySearch(new int[]{12, 13}, 12));
    System.out.println(
        bs.binarySearch(new int[]{12, 13}, 11));
  }
}

輸出: