public class BinarySearch { public static void printArray(int[] a) { System.out.print("\nIndex i: "); for(int i=0; i< a.length; i++) System.out.printf("%2d, ", i); System.out.print("\nElement a[i]: "); for(int i=0; i< a.length; i++) System.out.printf("%2d, ", a[i]); System.out.println("\n\n"); } public static void main(String[] args) { int[] a= { 4, 7, 8, 10, 14, 21, 22, 36, 62, 77, 81, 91}; // Print the array printArray(a); // Search for the target using Binary Search // We assume that the array is already sorted in increasing order int target = 22; //int target = 72; // Try this target next int idx=-1; // if the target is found its index is stored here // initial values for the three search varaibles int first=0; int last= a.length-1; int mid= (first + last)/2; while(last >= first) { if( a[mid] == target) { idx=mid; // Found it! break; // exit the while loop } else if(a[mid] > target) { // don't search in a[mid] ... a[last] last = mid-1; } else { // don't search in a[first] ... a[mid] first = mid +1; } // recalculate mid for the next iteration mid = (first + last)/2; // integer division! } // end of while loop if(idx == -1) System.out.println("Target not found."); else System.out.println("Target found at index: " + idx); } }