View RSS Feed

fatabass

A recursive method for searching an array of integers...

Rating: 2 votes, 3.00 average.
by , 03-08-2012 at 09:49 PM (1262 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

Submit "A recursive method for searching an array of integers..." to Facebook Submit "A recursive method for searching an array of integers..." to Digg Submit "A recursive method for searching an array of integers..." to del.icio.us Submit "A recursive method for searching an array of integers..." to StumbleUpon Submit "A recursive method for searching an array of integers..." to Google

Tags: None Add / Edit Tags
Categories
Uncategorized

Comments