jumpSearch static method

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

Implementation

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

  int n = list.length;
  int step = sqrt(n).toInt(); // Block size to be jumped
  int prev = 0;

  // Jump through the list until we find a block where the target might be
  while (list[min(step, n) - 1].compareTo(target) < 0) {
    prev = step;
    step += sqrt(n).toInt();
    if (prev >= n) {
      return -1; // Element not found, return -1
    }
  }

  // Linear search within the identified block
  for (int i = prev; i < min(step, n); i++) {
    if (list[i] == target) {
      return i; // Element found, return its index
    }
  }

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