binarySearch static method

int binarySearch({
  1. required List<String> list,
  2. required String target,
  3. bool isSorted = false,
})

Binary search: searches the list using divide and conquer approach.

The list must be sorted. If not sorted, set isSorted to false and it will sort the list first.

Returns the index of the target element if found, otherwise -1.

Implementation

static int binarySearch({
  required List<String> list,
  required String target,
  bool isSorted = false,
}) {
  if (!isSorted) {
    list = List<String>.from(list)
        .quickSort(); // Sort the list if not already sorted
  }

  int left = 0;
  int right = list.length - 1;

  while (left <= right) {
    int mid = left + (right - left) ~/ 2; // Calculate mid index

    if (list[mid] == target) {
      return mid; // Element found, return its index
    } else if (list[mid].compareTo(target) < 0) {
      left = mid + 1; // Search in the right half
    } else {
      right = mid - 1; // Search in the left half
    }
  }

  return -1; // Element not found, return -1
}