You are on page 1of 3
Thank you for printing our content at www.domain-name.com. Please check back soon for new contents. Get (https://www.programiz.com/learn-java?utm_campaign=programiz- App homepage&utm_source=programiz-website-java-app-popup) lomain-name.com veourvimiygeyi In this example, we will learn to implement binary search algorithm in Java. To understand this example, you should have the knowledge of the following Java programming (/java-programming) topics: » Java while and do...while Loop (/java-programming/do-while-loop) » Java if..else Statement (/java-programming/if-else-statement) » Java Arrays (/java-programming/arrays) Example: Java Program to Implement Binary Search Algorithm Thank you for printing our content at www.domain-name.com. Please check back soon for new contents. Get (https://www.programiz.com/learn-java2utm_campaign=programiz- App homepage&utm_source=programiz-website-java-app-popup) www.domain-name.com ANU vanaryoearCnqane atrayts, at exemene, 2nt Low, ane nagny + // Repeat until the pointers low and high meet each other while (low <= high) { 71 get index of mid element int mid = low + (high - low) / 2; // if element to be searched is the mid element if (array[mid] == element) return mid; // if element is less than mid element // search only the left side of mid if (array[mid] < element) low = mid + 1; // if element is greater than mid element // search only the right side of mid else high = mid - 1; Output 1 Enter element to be searched 6 Element found at index 3 Here, we have used the Java Scanner Class (/java-programming/scanner) to take input from the user. Based on the input from user, we used the binary search to check if the element is present in the array. We can also use the recursive call to perform the same task. Thank you for printing our content at www.domain-name.com, Please check back soon for new contents. Get (https://www.programiz.com/learn-java2utm_campaign=programiz- b homepage&utm_source=programiz-website-java-app-popup) www.domain-name.com 41 (arrayumuy == exemeney return mid // Search the left half of mid if (array[mid] > element) return binarySearch(array, element, low, mid - 1) // Search the right half of mid return binarySearch(array, el nt, mid + 1, high); return -1 Here, the method binarySearch() is calling itself until the element is found or, the if) condition fails. If you want to learn more about the binary search algorithm, visit Binary Search Algorithm (/dsa/binary-search). Share on: olhttps://www.facebook.com/sharer/sharer.php? @fhttes: ‘twitter.com/intent/tweet? ttps://www.programiz.com/java- text=Check%20this%20amazing%2¢ programming/examples/binary-search) programming/examples/binary-sear: Did you find this article helpful? Related Examples Jeve Example

You might also like