Skip to content
TheChatArchiveThe Chat Archive
Human-written demonstration (OpenAssistant volunteers)· OpenAssistant (human-written)Hugging Face OpenAssistant Conversations (oasst2)

How to code binary search in Java? I want to search a number in an array.

In OpenAssistant data, “assistant” turns were written by human volunteers as demonstrations. They are not model outputs.
  1. User

    How to code binary search in Java? I want to search a number in an array.

  2. Assistant

    Here's an example of how you can code a binary search algorithm in Java: [code] public int binarySearch(int[] arr, int target) { int left = 0; int right = arr.length - 1; while (left <= right) { int mid = (left + right) / 2; if (arr[mid] == target) { return mid; } else if (arr[mid] < target) { left = mid + 1; } else { right = mid - 1; } } return -1; } [/code] In this implementation, the binary search algorithm takes an array of integers and the target value as input. It uses two pointers, left and right, to keep track of the current search interval. The algorithm repeatedly divides the search interval in half until it finds the target value or determines that it is not present. If the target value is found, the index at which it was found is returned. If the target value is not found, the function returns -1.

    It's important to note that for this binary search algorithm to work, the input array must be sorted in ascending order.

  3. User

    Why must the input array must be sorted in ascending order?

  4. Assistant

    The input array must be sorted in an ascending order for this algorithm to work. The logic compares the middle integer with the target integer, and relies on it be either equivalent, less or greater than the target to define the next search area by updating the left and right pointers. If it weren't sorted in ascending order, the pointers could be updated to an area of the array where the target does not exist, causing the while loop to terminate once left and right become equal.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.