簡體   English   中英

如何使用比較二叉搜索樹顯示數組的值?

[英]How can I show the value of array with the Binary Search Tree of Comparison?

我打算在數組中搜索值,是否需要創建一個方法來處理它? 比如數組記錄了32,21,13,44,22,我去比較找22。 我該如何實施?

    public class binarySearch {

    public static void main(String [] args) {
        int i = binarySearch(0, new int[]{32,21,13,44,22});
        System.out.println("Iterations: " + i);
    }

    public static int binarySearch(int key, int[] array) {
        int left = 0;
        int mid;
        int right = array.length - 1;
        int i = 0;
        while (left <= right) {
            mid = (left + right) / 2;
            int comp = Integer.compare(key, array[mid]);
            i++;
            if (comp < 0) {
                right = mid - 1;
            } else if (comp > 0) {
                left = mid + 1;
            } else {
                break; // success
            }
        }
        return i;
    }
}

我的最終答案在這里。 以后可能對大家有幫助。

public static int binarySearch(int key, int[] array) {

        int left = 0;
        int mid;
        int right = array.length - 1;
        int i = 0;
        while (left <= right) {
            mid = (left + right) / 2;
            int comp = Integer.compare(key, array[mid]);
            i++;
            if (comp < 0) {
                right = mid - 1;
            } else if (comp > 0) {
                left = mid + 1;
            } else {
                break; // success
            }
        }
        return i;

    }

如果你已經洗牌數組,你所能做的就是通過一個數組 go 並找到你的號碼。

BinarySearch僅適用排序數組。 我認為您的解決方案可能如下所示:

public static int binarySearch(int[] arr, int key) {
    Arrays.sort(arr);
    return Arrays.binarySearch(arr, key);
}

暫無
暫無

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

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