简体   繁体   English

如何使用比较二叉搜索树显示数组的值?

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

I going to do searching the value in the array, did I need to create a method to handle it?我打算在数组中搜索值,是否需要创建一个方法来处理它? For example, the array logged 32,21,13,44,22, and I going to find 22 of the comparison.比如数组记录了32,21,13,44,22,我去比较找22。 How can I implement this?我该如何实施?

    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;
    }
}

My final answer is here.我的最终答案在这里。 May help you all in the future.以后可能对大家有帮助。

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;

    }

If you have shuffled array , all you can do is go through an array and find your number.如果你已经洗牌数组,你所能做的就是通过一个数组 go 并找到你的号码。

BinarySearch works only with sorted array. BinarySearch仅适用排序数组。 I think your solution could look like this:我认为您的解决方案可能如下所示:

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