当前位置:网站首页>Binary search

Binary search

2022-06-26 03:37:00 kingsley1212

1、 Half algorithm or binary search

 // Two points search 
    private void binarySearch() {
        // Define an array 
        int[] list = new int[]{1, 3, 5, 14, 35, 46, 67, 109, 800, 2345};
        //  The data you need to find , Determine where the value is in the array 
        int targetData = 800;// Suppose you want to know the location of this data 
        //  Starting position ( The subscript of the first data )
        int start = 0;
        // Last position 
        int end = list.length - 1;// The subscript of the last data )
        while (start < end) {
            // Get the subscript of the intermediate field , And if it is greater than the target number , After the compromise, the subscript needs to be added with the subscript of the starting position 
            int middle = start + (end - start) / 2;
            // If the target data is less than the number of intermediate subscripts , Just subtract the middle subscript number by one to become the last number, and then , Half after cycle 
            if (targetData < list[middle]) {
                end = middle - 1;
                // If the target data is greater than the number of intermediate subscripts ,
                //  The middle subscript minus one becomes the first number plus one , Because it is smaller than him , So it can't be equal to him ,
                // So add one 
            } else if (targetData > list[middle]) {
                start = middle + 1;
            } else {
                // Then we get the subscript position , The subscript number is middle
                targetData = list[middle];
            }
        }

    }
原网站

版权声明
本文为[kingsley1212]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202180547452788.html