abhpd / hacktoberfest2021

🌱 Contribute your favorite 📚 Data Structure implementation, 🕸 Algorithms, and 🎲 Projects. 😊 | Very Active Repository, Star and Share with your friends |
MIT License
543 stars 1.58k forks source link

Binary search in Java #2093

Open justdoit254 opened 2 years ago

justdoit254 commented 2 years ago

Algorithm and code of Binary search

anesha1 commented 2 years ago

The algorithm for Binary search is quiet easy .Here it is: public int runBinarySearchIteratively( int[] sortedArray, int key, int low, int high) { int index = Integer.MAX_VALUE;

while (low <= high) {
    int mid = low  + ((high - low) / 2);
    if (sortedArray[mid] < key) {
        low = mid + 1;
    } else if (sortedArray[mid] > key) {
        high = mid - 1;
    } else if (sortedArray[mid] == key) {
        index = mid;
        break;
    }
}
return index;

}

Now if we implement the above algorithm into a code, that will be: BinarySearch_Java.docx

Sandyy07 commented 1 year ago

Hi @abhpd , Kindly please assign me this issue.