ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Groovy Binary Search Implementation

Groovy

Goal -- WPM

Ready
Exercise Algorithm Area
1class BinarySearcher {
2
3/**
4* Performs binary search on a sorted array of integers.
5*
6* @param sortedArray The array to search within. Must be sorted in ascending order.
7* @param target The value to search for.
8* @return The index of the target value if found, otherwise -1.
9*/
10int search(int[] sortedArray, int target) {
11if (sortedArray == null || sortedArray.length == 0) {
12return -1; // Target not found in empty or null array
13}
14
15int low = 0;
16int high = sortedArray.length - 1;
17
18while (low <= high) {
19int mid = low + (high - low) / 2; // Prevent potential overflow
20
21if (sortedArray[mid] == target) {
22return mid; // Target found
23} else if (sortedArray[mid] < target) {
24low = mid + 1; // Target is in the right half
25} else {
26high = mid - 1; // Target is in the left half
27}
28}
29
30return -1; // Target not found
31}
32
33/**
34* Helper method to demonstrate usage (optional).
35*/
36void demonstrate() {
37int[] data = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91]
38int target1 = 23
39int target2 = 100
40
41println "Searching for " + target1 + " in " + data.toString() + ": " + search(data, target1)
42println "Searching for " + target2 + " in " + data.toString() + ": " + search(data, target2)
43}
44}
Algorithm description viewbox

Groovy Binary Search Implementation

Algorithm description:

This Groovy code implements the binary search algorithm to efficiently find a target value within a sorted array of integers. It repeatedly divides the search interval in half. This algorithm is fundamental for searching in large datasets where performance is critical, such as in databases or lookup tables.

Algorithm explanation:

Binary search works by repeatedly dividing the search interval in half. It starts with an interval covering the whole array. If the value of the search key is less than the item in the middle of the interval, the search narrows to the lower half. Otherwise, it narrows to the upper half. This process continues until the value is found or the interval is empty. The time complexity is O(log n) because the search space is halved in each step. The space complexity is O(1) for the iterative version. Edge cases include an empty or null array, and the target being smaller than the smallest element or larger than the largest element, all of which are handled by the loop termination and return value of -1.

Pseudocode:

function binarySearch(sortedArray, target):
  if sortedArray is null or empty:
    return -1

  low = 0
  high = length of sortedArray - 1

  while low <= high:
    mid = low + (high - low) / 2

    if sortedArray[mid] == target:
      return mid
    else if sortedArray[mid] < target:
      low = mid + 1
    else:
      high = mid - 1

  return -1