hello
- User
hello
- Assistant
Hello! How can I assist you today?
- User
provide java code for binary seacrch
- Assistant
Certainly! Binary search is an efficient algorithm for finding an item from a sorted list of items. It works by repeatedly dividing in half the portion of the list that could contain the item until you've narrowed the possible locations to just one.
Below is a simple example of a binary search implementation in Java. This code assumes that you are searching for an integer value in an array of integers that is already sorted in ascending order.
public class BinarySearch { // Binary search function public static int binarySearch(int[] arr, int target) { int left = 0; int right = arr.length - 1; while (left <= right) { int mid = left + (right - left) / 2; // Check if the target is present at mid if (arr[mid] == target) return mid; // If target greater, ignore left half if (arr[mid] < target) left = mid + 1; // If target is smaller, ignore right half else right = mid - 1; } // If we reach here, then the element was not present return -1; } public static void main(String[] args) { int[] arr = {-3, 10, 11, 25, 36, 47, 58, 69}; int target = 25; int result = binarySearch(arr, target); if (result == -1) System.out.println("Element not present"); else System.out.println("Element found at index: " + result); } }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.