Wednesday, August 24, 2022

BINARY SEARCH

 #include <bits/stdc++.h>

using namespace std;

 

int Binary_Search(int Arr[], int low, int high, int key)

{

    while (low <= high) {

        int middle = low + (high - low) / 2;

 

        if (Arr[middle] == key)

            return middle;

        if (Arr[middle] < key)

            low = middle + 1;

 

        else

            high = middle - 1;

    }

 

    return -1;

}

 

int main(void)

{

    int arr[] = {38, 4, 8, 38, 56, 27, 32, 38, 45};

    int len = sizeof(arr) / sizeof(arr[0]);

    int key = 38;

    int result = Binary_Search(arr, 0, len - 1, key);

    if(result == -1)

    cout << "Element not found" ;

    else

    cout << "Element found at index " << result+1;

    return 0;

}

No comments:

Post a Comment

CONSTRUCTURE IN PARENT CLASS

class Parent {     public Parent()     {         System.out.println("Parent Constrcutor");     }              } class Child extend...