簡體   English   中英

使用二進制搜索在數組中查找值(Java)

[英]Using Binary Search to find a value in an Array (Java)

我需要使用二進制搜索在數組中找到45.3。 到目前為止,這就是我所擁有的。

public class Bsearch {
    public static final int NOT_FOUND = -1;

    public static int binarySearch(int[] a, int x) {
        int low = 0;
        int high = a.length - 1;
        int mid;
        while (low <= high) {
            mid = (low + high) / 2;
            if (a[mid].compareTo(x) < 0)
                low = mid + 1;
            else if (a[mid].compareTo(x) > 0)
                high = mid - 1;
            else
                return mid;
        }
        return NOT_FOUND;
    }

    public static void main(String[] args) {
        int SIZE = 6;
        int[] a = new Integer[SIZE] = { 10, -3, 5, 24, 45.3, 10.5 };
        System.out.println("45.3 Found" + binarySearch(a, 45.3));
    }
}

我所有的錯誤似乎都源於這一領域-

    int [] a = new Integer [ SIZE ]={ 10,-3,5,24,45.3,10.5 };
    System.out.println("45.3 Found" +binarySearch(a, 45.3));

這一切對我來說都是新的,對於任何明顯的錯誤,我們深表歉意。

問題確實在此行中:

int[] a = new Integer[SIZE] = { 10, -3, 5, 24, 45.3, 10.5 };

存在許多問題:

  1. 您不能將Integer[]分配給int[]變量。 將其更改為new int[]
  2. 您不能將浮點數放在整數數組中; 將數字45.3和10.5更改為整數。
  3. 在Java中,您有兩個選擇:使用new運算符創建新數​​組時,您可以指定數組的大小或內容。

所以:

int[] a = new int[SIZE];

要么

int[] a = new int[] { 10, -3, 5, 24, 45, 10 };

兩者都會起作用。


您必須決定是否要使用類包裝器( Integer )的原始類型( int )並堅持使用。

您的方法binarySearchint[]作為參數,但是您使用的方法( compareTo )僅在Integer可用。

但是實際上,與原始類型進行比較要簡單得多:

       if (a[mid] < x)
            low = mid + 1;
        else if (a[mid] > x)
            high = mid - 1;
        else
            return mid;

對於二進制搜索,應對數據數組進行排序,並以正確的順序排序,但是傳遞給binarySearch(int [] a,int x)的數組未排序,因此請先對數組進行排序,然后對其進行二進制搜索。 還要檢查二進制搜索的邏輯,您正在將中間元素與0比較,並將其與要搜索的元素進行比較(鍵)

while(high >= low) {
  int middle = (low + high) / 2;
  if(data[middle] == key) {
     return true;
  }
  if(data[middle] < key) {
  low = middle + 1;
  }
  if(data[middle] > key) {
  high = middle - 1;
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM