Java Question Data structure 07

Consider the following array of sorted integers. 

10,15,25,30,33,34,46,55,78,84,96,99 

Using binary search algorithm, search for 23.


//Q7.java
public class Q7
{
    public static void binarySearch(int[] arr,int num)
    {
        
        //initialize low mid and high
        int low=0;
        int high=arr.length-1;
        int mid =0;
        
        //binary search logic
        while(low <= high)
        {
            mid=(low+high)/2;
            
            //if arr[mid] is equal to search element
            if(arr[mid]==num)
            {
                System.out.println("Value found at : "+mid);
                break;
            }
            else if(arr[mid]>num)
            {
                //less than the mid point element
                high=mid-1;
            }
            else if(arr[mid]<num)
            {
                //greater than the mid point element
                low=mid+1;
            }
        }
        
        //if value not found
        if(low>high)
        {
            System.out.println("Value not found");
        }
    }
    
    public static void main(String[] args){
        int[] arr={10,15,25,30,33,34,46,55,78,84,96,99};
        
        int key=23;
        binarySearch(arr, key);
    }
}








download code

Comments

Popular posts from this blog

Sample Qustion 11

Sample Qustion 1

Sample Qustion 5