JAVA binary search method

The binary search method is to find a number val in an array sorted from small to large, first compare the number val to be found with the middle value, if it is larger than the middle value, then search on the right side of the middle value; if it is smaller than the middle value , then look to the left of the median. keep recursing. Know to find val. If not found, the output has no relevant data in the sequence.

public class Test2 {

        public static void main(String[] args) {
           
            int [] arr ={1, 5, 9 ,56, 78, 80, 85, 99}; // Note that the array needs to be sorted from small to large. 
                       
            binaryFind( 0, arr.length-1, 85 , arr);
        }
         /** 
         * @author  
         * @param left array left subscript
         * @param right array is subscripted again
         * @param arr array reference
         * @param val the number to be found
         * @Function: To find out whether there is a val number in a bunch of numbers, the premise of calling this binary search method is that the sequence arr is ordered
         */
        public static void binaryFind(int left, int right, int val,int [] arr)
        {
            
            if (left <= right) // The binary search is actually traversing the array, and the left subscript must be no greater than the right subscript 
            {
               
                int pivot =arr[(left+right)/2]; // find the middle number
                
                if (val < pivot) // If the number to be found is smaller than the middle value, look for 
                { on the left of the middle value
                    binaryFind( left, (left + right)/2-1, val, arr);
                } else  if (val > pivot) // If the number you are looking for is greater than the middle value, look to the right of the middle value
                   
                {
                    binaryFind( (left + right)/2 +1, right, val, arr);
                }else if(val == pivot)
                {
                    System.out.println( "The number "+val+" was found in the array sequence, its subscript is: "+( (left+right)/2 ) );
                }
            }
            else
            {
                System.out.println( "Unfortunately the number you are looking for is not in the array sequence" );
            }

        }
    
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325895784&siteId=291194637
Recommended