I tried to get this code to work. I have to create a generic binary version of binary search. I'm not sure how to compare two common types without a comparable interface
import java.util.ArrayList; public class BinarySearcher<T> { private T[] a; public BinarySearcher(T[] words) { a = words; } public int search(T v) { int low = 0; int high = a.length - 1; while (low <= high) { int mid = (low + high) / 2; T midVal = a[mid]; if (v.compareTo(midVal) < 0) { low = mid - 1; } else if (v.compareTo(midVal) > 0) { high = mid + 1; } } return -1; } public int compareTo(T a) { return this.value.compare - b; } }
This is the tester class:
import java.util.Arrays; import java.util.Scanner; public class BinarySearchTester { public static void main(String[] args) { String[] words = {"Alpha", "Bravo", "Charlie", "Delta", "Echo", "Foxtrot", "Golf", "Hotel", "India", "Juliet", "Kilo", "Lima", "Mike", "November", "Oscar", "Papa", "Quebec", "Romeo", "Sierra", "Tango", "Uniform", "Victor", "Whiskey", "X-Ray", "Yankee", "Zulu"}; BinarySearcher<String> searcher = new BinarySearcher<String>(words); System.out.println(searcher.search("November")); System.out.println("Expected: 13"); System.out.println(searcher.search("October")); System.out.println("Expected: -1"); } }
source share