Showing posts with label Data structure. Show all posts
Showing posts with label Data structure. Show all posts

Thursday, 15 February 2024

           Binary Search Code in java without recursion

class BinarySearchExample{  

    public static void binarySearch(int arr[], int low, int high, int key){  

        int mid = (low + high)/2;  

        while( low <= high ){  

            if ( arr[mid] < key ){  

                low = mid + 1;     

            } else if ( arr[mid] == key ){  

                System.out.println("Element is found at index: " + mid);  

                break;  

            } else {  

                high = mid - 1;  

            }  

            mid = (low + high)/2;  

        }  

        if ( low > high ){  

            System.out.println("Element is not found!");  

        }  

    }  


    public static void main(String args[]){  

        int arr[] = {15,24,32,35,42,50};  

        int key = 32;  

        int high = arr.length - 1;  

        binarySearch(arr, 0, high, key);     

    }  

}  


OUTPUT

Element is found at index: 2

Data Structure Programs

                                                 Binary Search Code in java using Recursion



class BinarySearchExample1{  

    public static int binarySearch(int arr[], int first, int last, int key)

    {  

        if (last>=first)

        {  

            int mid = first + (last - first)/2;  

            if (arr[mid] == key)

            {  

            return mid;  

            }  

            if (arr[mid] > key)

            {  

            return binarySearch(arr, first, mid-1, key);//search in left subarray  

            }else

            {  

            return binarySearch(arr, mid+1, last, key);//search in right subarray  

            }  

        }  

        return -1;  

    }  

    public static void main(String args[]){  

        int arr[] = {20,40,50,60,70};  

        int key = 40;  

        int last=arr.length-1;  

        int result = binarySearch(arr,0,last,key);  

        if (result == -1)  

            System.out.println("Element is not found!");  

        else  

            System.out.println("Element is found at index: "+result);  

    }  

}  


OUTPUT

Element is found at index: 1

DBMS NOTES UNIT 3

                                                              UNIT 3  ER (Entity Relationship) An entity-relationship model is known as an E...