java binary search application examples

  • 2020-10-31 21:45:03
  • OfStack

java 2 - point method to find an application instance

The premise of the 2 - point search is: the array is ordered

Note: Dynamic change of mid, otherwise error!!

Example code:


public class BiSearch { 
    public static void main(String[] args) { 
    new BiSearch().biFind(new int []{1,2,3,4,5,6,7},3); 
  } 
    public void biFind(int arr[],int y){ 
    int start=0; 
    int end=arr.length-1; 
    int mid=(start+end)/2; 
     
    while(start<=end){ 
      if(y==arr[mid]){ 
            System.out.println(" The search was successful with a subscript of "+mid); 
         break; 
      } 
      if(y>arr[mid]){ 
           start=mid+1; 
           mid=(start+end)/2; 
         } 
      if(y<arr[mid]){ 
           end=mid-1; 
           mid=(start+end)/2; 
        } 
      if(start>end){ 
        System.out.println(" To find the failure "); 
 
      } 
    } 
  } 
} 

If you have any questions, please leave a message or go to this site community exchange discussion, thank you for reading, I hope to help you, thank you for your support to this site!


Related articles: