Skip to content

Instantly share code, notes, and snippets.

@mushifali
Created April 26, 2018 16:07
Show Gist options
  • Save mushifali/5e39c68bed88d1cfa397b0298fc4fc88 to your computer and use it in GitHub Desktop.
Save mushifali/5e39c68bed88d1cfa397b0298fc4fc88 to your computer and use it in GitHub Desktop.
This is Binary Search Implementation in Java
/**
* @author Mushif Ali Nawaz
*/
public class AlgorithmImpl {
public static void main(String[] args) {
String[] names = {"Ahmed", "Aslam", "Mushif", "Shakeel", "Waqas"};
int index = AlgorithmImpl.binarySearch(names, "Shakeel");
System.out.println("For Shakeel: Binary Search returned " + index + " index.");
index = AlgorithmImpl.binarySearch(names, "Shahid");
System.out.println("For Shahid: Binary Search returned " + index + " index.");
Integer[] numbers = {2, 5, 7, 9, 13, 15, 29, 55, 97};
index = AlgorithmImpl.binarySearch(numbers, 15);
System.out.println("For 15: Binary Search returned " + index + " index.");
index = AlgorithmImpl.binarySearch(numbers, 100);
System.out.println("For 100: Binary Search returned " + index + " index.");
}
public static <T extends Comparable<T>> int binarySearch (T[] sortedArray, T value) {
return binarySearch(sortedArray, value, 0, sortedArray.length-1);
}
private static <T extends Comparable<T>> int binarySearch(T[] sortedArray, T value, int left, int right) {
if(left > right)
return -left;
int mid = (left + right) / 2;
int c = value.compareTo(sortedArray[mid]);
return (c == 0) ? mid : (c < 0) ?
binarySearch(sortedArray, value, left, mid - 1) :
binarySearch(sortedArray, value, mid + 1, right);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment