Skip to content

Instantly share code, notes, and snippets.

@AnimeshShaw
Created September 19, 2013 20:20
Show Gist options
  • Select an option

  • Save AnimeshShaw/6629272 to your computer and use it in GitHub Desktop.

Select an option

Save AnimeshShaw/6629272 to your computer and use it in GitHub Desktop.
Binary Search Algorithm implemented in Java. This code can be used to search for integers or characters or Strings or a combination of all. Binary search assumes that the input array or elements are sorted but this code with sort them after you enter the array. Get the sorting code from here :- https://gist.github.com/PsychoCoderHC/6541791
import Sorts.InsertionSort;
import java.util.Scanner;
public class BinarySearch {
public int binarySearch(Comparable[] a, Comparable key) {
int low = 0, high = a.length - 1,mid;
while (low <= high) {
mid = low + (high - low) / 2;
if(key.compareTo(a[mid])< 0 ) high = mid -1;
else if(key.compareTo(a[mid])>0) low = mid +1;
else return mid;
}
return -1;
}
public static void main(String[] args) {
String a;
String[] b;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the numbers or characters you want to search for on a single line seperated by a space");
a = sc.nextLine();
b = a.trim().split(" ");
System.out.println("Enter the element you want to search for :-");
a=sc.nextLine();
InsertionSort.InsertionSort(b);
System.out.println("\nThe sorted array is :-");
for (int i=0;i<b.length;i++){
System.out.print(b[i]+" ");
}
int pos = new BinarySearch().binarySearch(b, a);
if (pos!=-1){
System.out.println("\n\nElement found at position :-"+(pos+1));
}else{
System.out.println("\nElement Not found");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment