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

No comments:

Post a Comment

DBMS NOTES UNIT 3

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