Writing a binary search for an array of random ints. When in comes time to pick a target value and search for it, the program will not identify the number. If you run it you'll see what I mean
/* Exercise4.java Binary Search */ import java.io.*; import java.util.*; public class Exercise4 { private static final int NOT_FOUND = -1; // this value GLOBAL to file - visible in ALL methods in this file public static void main( String args[] ) { Scanner kbd = new Scanner(System.in); Random rand = new Random(); if (args.length < 1 ) { System.out.println("\n\n !! You must enter a desired array length on the cmd line !!\n"); System.exit(0); } int array[] = new int[ Integer.parseInt(args[0]) ]; int count=0; for (int i=0 ; i < array.length ; ++i ) { int r = 1 + rand.nextInt(100); if ( binarySearch( array, r ) == NOT_FOUND ) { insertInOrder( array, count, r ); ++count; } // else ignore this value its already in the array - no dupes to be inserted } printArray( array ); do { System.out.print("number to search for (negative to quit)? "); int target = kbd.nextInt(); if (target < 0) break; int index=binarySearch( array, target ); if (index >= 0) System.out.printf("%d FOUND in array at index position %d\n",target,index ); else System.out.printf("%d NOT found in array\n",target ); } while (true); } // END MAIN private static void printArray( int array[] ) { System.out.printf("\nArray has %d values:\n",array.length ); for( int i=0 ; i<array.length ;++i ) System.out.print(array[i] + " " ); System.out.println("\n"); } // puts the new value into the array at its proper sorted position by shuffline higher values up one place // and opening up a hole where the new val goes. All values are kept contiguous from the front private static void insertInOrder( int array[], int count, int newVal ) { int i; for (i=count-1; i>=0 && newVal<array[i] ; --i) array[i+1] = array[i]; array[i+1] = newVal; } // if target not found returns -1 // else returns index position where target found public static int binarySearch( int array[], int target ) { int low=0; int high=array.length; int spot=(low+high)/2; int i=0; while (i==0) { if (array[spot]<target) { low=spot+1; break; } else if(array[spot]>target) { high=spot-1; break; } else if (array[spot]==target) return spot; } return NOT_FOUND; } } //END class