A recursive method for searching an array of integers...
by , 03-08-2012 at 08:49 PM (698 Views)
Java Code:public class ArrayLister { private static int arraySearcher(int[] arrayToSort,int numberToFind,int left,int right){ int middle = (left + right) / 2 ; System.out.println(middle); if(middle==arrayToSort.length-1) { if(arrayToSort[middle] == numberToFind) { return middle; } else return -1; } if(arrayToSort[middle] == numberToFind) { return middle; } else if(arrayToSort[middle] < numberToFind ) { left = middle; return ArrayLister.arraySearcher(arrayToSort, numberToFind, left, right); } else{ right = middle; return ArrayLister.arraySearcher(arrayToSort, numberToFind, left, right); } } public static int arraySearch(int[] arrayToSort, int numberToFind ) { int left = 0; int right = (arrayToSort.length); int result = ArrayLister.arraySearcher(arrayToSort, numberToFind, left, right); return result; } } public class TestClass { public static void main(String args[]) { int[] myIntArray = new int[] {0,1,2,3,4,5,6,7,8,9}; int numberToFind = 9; Integer answer = ArrayLister.arraySearch(myIntArray, numberToFind); if(answer==-1) { System.out.println("The value you are looking for does not exist in the array."); } // end statement if else{ System.out.println("The value: " + numberToFind + " is at index: "+ answer); } // end statement else } // end method main } // end class Test Class










Email Blog Entry
He Does not Look Jamaican Ray Ban...
Today, 10:36 PM in Java Software