BinarySearch.java - import java.util.Arrays import...

This preview shows page 1 - 2 out of 2 pages.

import java.util.Arrays;import java.util.Comparator;/*** @author Elise Reach([email protected])* @version 2020-10-04*/public class BinarySearch {/*** @param a the array to be searched through* @param key a search value* @param comparator compares and sorts the array to key* @param <Key> ???* @return the index target in a or -1*/public static <Key> int firstIndexOf(Key[] a, Key key, Comparator<Key> comparator) {if (a == null || key == null || comparator == null) {throw new NullPointerException();}Arrays.sort(a, comparator);int firstIndex = -1;int left = 0;int right = a.length - 1;int mid = 0;while (left <= right) {mid = (left + right) / 2;if (comparator.compare(key, a[mid]) < 0) {right = mid - 1;}else if (comparator.compare(key, a[mid]) > 0) {left = mid + 1;}else {firstIndex = mid;

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture