Finding Max value in an array using recursion - java

For one of the questions i was asked to solve, I found the max value of an array using a for loop, so i tried to find it using recursion and this is what I came up with:
public static int findMax(int[] a, int head, int last) {
int max = 0;
if (head == last) {
return a[head];
} else if (a[head] < a[last]) {
return findMax(a, head + 1, last);
} else {
return a[head];
}
}
So it works fine and gets the max value, but my question is : is it ok to have for the base case return a[head] and for the case when the value at the head is > the value at last?

You could just as easily do it with only one counter, just the index of the value you want to compare this time:
public static int findMax(int[] a, int index) {
if (index > 0) {
return Math.max(a[index], findMax(a, index-1))
} else {
return a[0];
}
}
This much better shows what is going on, and uses the default "recursion" layout, e.g. with a common base step. Initial call is by doing findMax(a, a.length-1).

It's actually much simpler than that. The base case is if you've reached the end of the array (the 'else' part of the ternary control block below). Otherwise you return the max of the current and the recursive call.
public static int findMax(int[] a) {
return findMax(a, 0);
}
private static int findMax(int[] a, int i) {
return i < a.length
? Math.max(a[i], findMax(a, i + 1))
: Integer.MIN_VALUE;
}
At each element, you return the larger of the current element, and all of the elements with a greater index. Integer.MIN_VALUE will be returned only on empty arrays. This runs in linear time.

I would solve this by dividing the array in to the half on each recursive call.
findMax(int[] data, int a, int b)
where a and b are array indices.
The stop condition is when b - a <= 1, then they are neighbours and the max is max(a,b);
The initial call:
findMax(int[] data, int 0, data.length -1);
This reduces the maximum recursion depth from N to log2(N).
But the search effort still stays O(N).
This would result in
int findMax(int[] data, int a, int b) {
if (b - a <= 1) {
return Math.max(data[a], data[b]);
} else {
int mid = (a+b) /2; // this can overflow for values near Integer.Max: can be solved by a + (b-a) / 2;
int leftMax = findMax(a, mid);
int rightMax = findMax(mid +1, b);
return Math.max(leftMax, rightMax);
}
}

I came across this thread and it helped me a lot. Attached is my complete code in both recursion and divide&conquer cases.
The run time for divide&conquer is slightly better than recursion.
//use divide and conquer.
public int findMaxDivideConquer(int[] arr){
return findMaxDivideConquerHelper(arr, 0, arr.length-1);
}
private int findMaxDivideConquerHelper(int[] arr, int start, int end){
//base case
if(end - start <= 1) return Math.max(arr[start], arr[end]);
//divide
int mid = start + ( end - start )/2;
int leftMax =findMaxDivideConquerHelper(arr, start, mid);
int rightMax =findMaxDivideConquerHelper(arr, mid+1, end);
//conquer
return Math.max( leftMax, rightMax );
}
// use recursion. return the max of the current and recursive call
public int findMaxRec(int[] arr){
return findMaxRec(arr, 0);
}
private int findMaxRec(int[] arr, int i){
if (i == arr.length) {
return Integer.MIN_VALUE;
}
return Math.max(arr[i], findMaxRec(arr, i+1));
}

What about this one ?
public static int maxElement(int[] a, int index, int max) {
int largest = max;
while (index < a.length-1) {
//If current is the first element then override largest
if (index == 0) {
largest = a[0];
}
if (largest < a[index+1]) {
largest = a[index+1];
System.out.println("New Largest : " + largest); //Just to track the change in largest value
}
maxElement(a,index+1,largest);
}
return largest;
}

I know its an old Thread, but maybe this helps!
public static int max(int[] a, int n) {
if(n < 0) {
return Integer.MIN_VALUE;
}
return Math.max(a[n-1], max(a, n - 2));
}

class Test
{
int high;
int arr[];
int n;
Test()
{
n=5;
arr = new int[n];
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
high = arr[0];
}
public static void main(String[] args)
{
Test t = new Test();
t.findHigh(0);
t.printHigh();
}
public void printHigh()
{
System.out.println("highest = "+high);
}
public void findHigh(int i)
{
if(i > n-1)
{
return;
}
if(arr[i] > high)
{
high = arr[i];
}
findHigh(i+1);
return;
}
}

You can do it recursively as follows.
Recurrent relation it something like this.
f(a,n) = a[n] if n == size
= f(a,n+1) if n != size
Implementation is as follows.
private static int getMaxRecursive(int[] arr,int pos) {
if(pos == (arr.length-1)) {
return arr[pos];
} else {
return Math.max(arr[pos], getMaxRecursive(arr, pos+1));
}
}
and call will look like this
int maxElement = getMaxRecursive(arr,0);

its not okay!
your code will not find the maximum element in the array, it will only return the element that has a higher value than the elements next to it, to solve this problem,the maximum value element in the range can be passed as argument for the recursive method.
private static int findMax(int[] a, int head, int last,int max) {
if(last == head) {
return max;
}
else if (a[head] > a[last]) {
max = a[head];
return findMax(a, head, last - 1, max);
} else {
max = a[last];
return findMax(a, head + 1, last, max);
}
}

Optimized solution
public class Test1 {
public static int findMax(int[] a, int head, int last) {
int max = 0, max1 = 0;
if (head == last) {
return a[head];
} else if (a[head] < a[last]) {
max = findMax(a, head + 1, last);
} else
max = findMax(a, head, last - 1);
if (max >= max1) {
max1 = max;
}
return max1;
}
public static void main(String[] args) {
int arr[] = {1001, 0, 2, 1002, 2500, 3, 1000, 7, 5, 100};
int i = findMax(arr, 0, 9);
System.out.println(i);
}
}

Thanks #Robert Columbia for the suggestion!
Update: This following function is going to recursively start from index 0 and it will keep adding to this index value till it's equal to the Length of the array, if it's more we should stop and return 0. Once we're doing that, we need to get the max of every two items in the array so, for example:
A = [1 , 2 , 3 ];
A[0] ( 1 ) vs A[1] ( 2 ) = 2
A[1] ( 2 ) vs A[2] ( 3 ) = 3
Max(2,3) = 3 ( The answer )
public int GetMax(int [] A, int index) {
index += 1;
if (index >= A.Length) return 0;
return Math.Max(A[index], GetMax(A, index + 1));
}

static int maximumOFArray(int[] array,int n) {
int max=Integer.MIN_VALUE;
if(n==1) return array[0];
else
max=maximumOFArray(array, --n);
max= max>array[n] ? max : array[n];
return max;
}

private static int getMax(int [] arr, int idx) {
if (idx==arr.length-1 ) return arr[idx];
return Math.max(arr[idx], getMax (arr,idx+1 ));
}

public class FindMaxArrayNumber {
public static int findByIteration(int[] array) {
int max = array[0];
for (int j : array) {
max = Math.max(j, max);
}
return max;
}
public static int findByRecursion(int[] array, int index) {
return index > 0
? Math.max(array[index], findByRecursion(array, index - 1))
: array[0];
}
public static void main(String[] args) {
int[] array = new int[]{1, 2, 12, 3, 4, 5, 6};
int maxNumberByIteration = findByIteration(array);
int maxNumberByRecursion = findByRecursion(array, array.length - 1);
System.out.println("maxNumberByIteration: " + maxNumberByIteration);
System.out.println("maxNumberByRecursion: " + maxNumberByRecursion);
// Outputs:
// maxNumberByIteration: 12
// maxNumberByRecursion: 12
}
}

int maximum = getMaxValue ( arr[arr.length - 1 ], arr, arr.length - 1 );
public static int getMaxValue ( int max, int arr[], int index )
{
if ( index < 0 )
return max;
if ( max < arr[index] )
max = arr[index];
return getMaxValue ( max, arr, index - 1 );
}
I felt that using a tracker for current maximum value would be good.

Related

Count occurrences of a given integer in an array using recursion

Without using a loop, I'm trying to count the number of times a given integer is in an array using recursion. I keep getting a StackOverflow error and I can't figure out why.
public static int countOccurrences(int[] arr, int n) {
if (arr.length == 0) {
return 0;
}
if (arr[0] == n) {
return 1 + countOccurrences(arr, n - 1);
}
return countOccurrences(arr, n - 1);
}
}
If you can use only two parameters, then try:
public static int countOccurrences(int[] arr, int n) {
if (arr.length == 0) {
return 0;
}
if (arr[0] == n) {
return 1 + countOccurrences(Arrays.copyOfRange(arr, 1, arr.length), n);
}
return countOccurrences(Arrays.copyOfRange(arr, 1, arr.length), n);
}
the problem with above code is that the base condition will never be satisfied as you are never trying to reduce the length of the array. To keep track of length traversed, you can use a variable that starts from end to start ( or from start to end your choice ) . And let's say , num is the value that you want to count. Then you can change your code to like this :
public class CountFrequency {
public static void main(String[] args) {
int A[] = { 1, 2, 3, 4, 5, 5 };
int count = countOccurences(A, 5);
System.out.println(count);
}
private static int countOccurences(int[] arr, int num) {
return helper(arr, num, arr.length - 1);
}
private static int helper(int[] arr, int num, int i) {
if (i == -1) {
return 0;
}
if (arr[i] == num)
return 1 + helper(arr, num, i - 1);
else
return helper(arr, num, i - 1);
}
}
and the output is
2

Java divide and conquer algorithm stack overflow error

I am trying to find out the index of the smallest number in an int array using divide and conquer and I have this stack overflow error:
Exception in thread "main" java.lang.StackOverflowError
at java.lang.StrictMath.floor(Unknown Source)
at java.lang.Math.floor(Unknown Source)
This is my divide and conquer method:
private static int dC(int[] a, int f, int l) {
if(f == 1)
return f;
if(a[dC(a, f, (int)(Math.floor((double)(f+l)/2)))] > a[dC(a, (int)(Math.floor((double)(f+l)/2)+1), l)])
return dC(a, (int)(Math.floor((double)(f+l)/2)+1), l);
else
return dC(a, f, (int)(Math.floor((double)(f+l)/2)));
}
Here is what I put in my main method:
int[] a = {35,30,40,50};
System.out.println(dC(a, 0, 3));
You have a problem with your stoping "rule"
private static int dC(int[] a, int f, int l) {
if(l == f) // <-- This mean you have one item, so you want to return it.
return f;
if(a[dC(a, f, (int)(Math.floor((double)(f+l)/2)))] > a[dC(a, (int)(Math.floor((double)(f+l)/2)+1), l)])
return dC(a, (int)(Math.floor((double)(f+l)/2)+1), l);
else
return dC(a, f, (int)(Math.floor((double)(f+l)/2)));
}
Also, I would try to do the calculation only once, so something like this (also what Joop Eggen said about Integers arithmetics):
private static int dC(int[] a, int f, int l) {
if(l == f)
return f;
int m = (f+l) / 2;
int left = dC(a, f, m);
int right = dC(a, m+1, l);
if(a[left] > a[right])
return left;
else
return right;
}
This is just the classical binary search problem. From what I can glean by looking at your code, you seem to be getting bogged down in the logic used to make each recursive call to the left and right subarrays of the current array. The logic I used below is to take everything from the start to (start+end)/2 for the left recursion, and everything from ((start+end)/2) + 1 to end for the right recursion. This guarantees that there would never be any overlap.
The base case occurs when the algorithm finds itself sitting on a single entry in the array. In this case, we just return that value, and we do not recurse further.
private static int dC(int[] a, int start, int end) {
if (start == end) return a[start];
int left = dC(a, start, (start+end)/2);
int right = dC(a, ((start+end)/2) + 1, end);
return left < right ? left : right;
}
public static void main(String args[])
{
int[] a = {10, 3, 74, 0, 99, 9, 13};
System.out.println(dC(a, 0, 6)); // prints 0
}
Demo
Note: I have no idea what role Math.floor would be playing here, since you're using arrays of integer numbers, not doubles or floats. I removed this, because I saw no need for it.
It's a typical problem locating the index to the min/max, you can try it as:
public static void main(String... args) {
int[] arr = generateArrays(100, 1000, 0, 10000, true);
int minIndex = findMinIndex(arr, 1, arr.length - 1);
int theMin = arr[minIndex];
Arrays.sort(arr);
System.out.println(String.format("The min located correctly: %s", arr[0] == theMin));
}
private static int findMinIndex(int[] a, int l, int r) {
if (r - l < 1) return l;
int mid = l + (r - l) / 2;
int lIndex = findMinIndex(a, l + 1, mid);
int rIndex = findMinIndex(a, mid + 1, r);
int theMinIndex = l;
if (a[lIndex] < a[theMinIndex]) theMinIndex = lIndex;
if (a[rIndex] < a[theMinIndex]) theMinIndex = rIndex;
return theMinIndex;
}
And the helper to generate a random array.
public static int[] generateArrays(int minSize, int maxSize, int low, int high, boolean isUnique) {
Random random = new Random(System.currentTimeMillis());
int N = random.nextInt(maxSize - minSize + 1) + minSize;
if (isUnique) {
Set<Integer> intSet = new HashSet<>();
while (intSet.size() < N) {
intSet.add(random.nextInt(high - low) + low);
}
return intSet.stream().mapToInt(Integer::intValue).toArray();
} else {
int[] arr = new int[N];
for (int i = 0; i < N; ++i) {
arr[i] = random.nextInt(high - low) + low;
}
return arr;
}
}

return recursivly the biggest values minus lowest value from array

I try to write recursive program that return the biggest value - smallest value from array.
So I write this: (this return me the biggest value)
public static void main(String[] args) {
int arr[] = {1 , 5 , 11, -2};
System.out.println(SumOfBiggestMinusLowestValue(arr, 0));
}
private static int SumOfBiggestMinusLowestValue(int[] arr, int index) {
if (index == arr.length-1 ) {
return arr[index];
}
return Math.max (arr[index] ,SumOfBiggestMinusLowestValue(arr, index+1));
}
I though to do this to return big-min:
return Math.max (arr[index] ,SumOfBiggestMinusLowestValue(arr, index+1)) - Math.min(arr[index] ,SumOfBiggestMinusLowestValue(arr, index+1))
but it's not work its giving me 7 instead 13, what I missing?
and from yours experience guys,how to think recursively?
Essentially when recursing you want to have changing values and have it return the final results when a specific criteria is met
I modified your code so that you pass in the array, followed by the initial index and set the min and max value to the first value in the array. It will recurse down and check if the next value in the array is greater than or less than the min and max and set accordingly. It will stop once the index is equal to the length of the array and return the final results:
public static void main(String[] args) {
int arr[] = {1 , 5 , 11, -2};
System.out.println(pow(arr, 0, arr[0], arr[0]));
}
public static int pow(int[] arr, int index, int min, int max) {
if (index == arr.length) {
return max - min;
}
int val = arr[index];
int newMin = val < min ? val : min;
int newMax = val > max ? val : max;
return pow(arr, index + 1, newMin, newMax);
}
Another way to do it based off Taras Sheremeta suggestion is something as follows:
public static void main(String[] args) {
int arr[] = {1 , 5 , 11, -2};
System.out.println(largest(arr, 0) - smallest(arr, 0));
}
public static int smallest(int[] arr, int index) {
if (index == arr.length - 1) {
return arr[index];
}
return Math.min(arr[index], smallest(arr, index + 1));
}
public static int largest(int[] arr, int index) {
if (index == arr.length - 1) {
return arr[index];
}
return Math.max(arr[index], largest(arr, index + 1));
}
the functions will find their respective largest and smallest values recursively.
Looks like the is some logical error in recursion. In the pow method functions Math.max(...) and Math.min(...) get a value from the array as the first argument and NOT a value from an array as the second argument. The result of pow function IS NOT a value from the array.
public static void main(String[] args) {
int arr[] = {1 , 5 , 11, -2};
System.out.println(pow(arr, 0, arr[0], arr[0]));
}
private static int pow(int[] arr, int index, int max, int min) {
if (index == arr.length) {
return max - min;
}
max = Math.max(max, arr[index]);
min = Math.min(min, arr[index]);
return pow(arr, index + 1, max, min);
}
You can read more about How should you approach recursion?

in a recursive method, find index of largest value in an array

//as the title says, i need to find the index of the largest value in an int //array, all of this needs to be done in one method this is what my helper //method looks like so far
it only returns last index in array i can easily return the max value but i cant figure out how to return the index of that value
//this is helper method
private int recursiveGetIndexOfLargest( int[] list, int count )
{
int index;
int[] y = list;
int temp = count - 1;
if( count > 0 )
{
index = Math.max( list[list.length - 1], list[temp] );
for(int x = 0; x < y.length; x++)
{
if(y[x] == index)
{
return x;
}
}
return recursiveGetIndexOfLargest(list, temp);
}
else
{
return -1;//empty list
}
}
this is method that calls helper
public int getIndexOfLargest()
{
return recursiveGetIndexOfLargest(list, count);
}
Try this one:
int recursiveGetIndexOfLargest(int[] list, int count)
{
if (count == list.length - 1) return count;
int index = recursiveGetIndexOfLargest(list, count + 1);
return list[count] > list[index] ? count : index;
}
int[] arr = {1, 5, 2, 3, 0};
System.out.println(recursiveGetIndexOfLargest(arr, 0));
int findLargestIndex(int[] array, int currentPos, int currentLargestIndex)
{
if(currentPos == array.length)
return currentLargestIndex;
if(array[currentPost] > array[currentLargestIndex]
return findLargestIndex(array,currentPos+1, currentPos);
else
return findLargestIndex(array,currentPos+1, currentLargestIndex);
}
It is actually a O(n) for loop done recursively.
You start it like this:
int result = findLargestIndex(array,0,0);
This would work but it will alter the array.
void findLargestIndex(int[] array, int currentPos)
{
if(currentPos == array.size()) return;
array[0] = (array[currentPos] < array[currenPos + 1] ? currentPos + 1 : currentPos;
findLargestIndex(int[] array, currentPos + 1);
}
The largest index will be storred at array[0] (This alters the array).
You simply start the function:
findLargestIndex(array,0);
Thank You tomse!!!!!!!!
the parameter count is actually the size of the array so i changed it a little to
private int recursiveGetIndexOfLargest( int[] list, int count )
{
int index;
int temp = count - 1;
if( temp == 0 )
{
return temp;
}
else
{
index = recursiveGetIndexOfLargest(list, temp);
return list[temp] > list[index] ? temp : index;
}
}
and now it works damn i wasted several hours failing

How to use recursion in creating a binary search algorithm

I have been using my time off university to practice Java through coding algorithms. One of the algorithms I coded was the binary search:
public class BinarySearch {
private static int list[] = {3, 6, 7, 8, 9, 10};
public static void main(String[] args) {
BinarySearch b = new BinarySearch();
b.binarySearch(list);
}
public void binarySearch(int[] args) {
System.out.println("Binary search.");
int upperBound = args.length;
int lowerBound = 1;
int midpoint = (upperBound + lowerBound) / 2;
int difference = upperBound - lowerBound;
int search = 7;
for (int i = 0; i < args.length; i++) {
if (search < args[midpoint - 1] && difference != 1) {
upperBound = midpoint - 1;
midpoint = upperBound / 2;
} else if (search > args[midpoint - 1] && difference != 1) {
lowerBound = midpoint + 1;
midpoint = (lowerBound + upperBound) / 2;
} else if (search == args[midpoint - 1]) {
midpoint = midpoint - 1;
System.out.println("We found " + search + " at position " + midpoint + " in the list.");
i = args.length;
} else {
System.out.println("We couldn't find " + search + " in the list.");
i = args.length;
}
}
}
}
I really want to be able to write a much cleaner and efficient binary search algorithm, an alternative to what I've coded. I have seen examples of how recursion is used such as when doing factorial with numbers which I understand. However when coding something of this complexity I am confused on how to use it to my advantage. Therefore my question is how do I apply recursion when coding a binary search algorithm. And if you have any tips for me to perfect my recursion skills even if it has to be something that doesn't regard to binary search then please feel free to post.
If you really want to use recursion, this should do it.
public static int binarySearch(int[] a, int target) {
return binarySearch(a, 0, a.length-1, target);
}
public static int binarySearch(int[] a, int start, int end, int target) {
int middle = (start + end) / 2;
if(end < start) {
return -1;
}
if(target==a[middle]) {
return middle;
} else if(target<a[middle]) {
return binarySearch(a, start, middle - 1, target);
} else {
return binarySearch(a, middle + 1, end, target);
}
}
Here is an easier way of doing binary search:
public static int binarySearch(int intToSearch, int[] sortedArray) {
int lower = 0;
int upper = sortedArray.length - 1;
while (lower <= upper) {
int mid = lower + (upper - lower) / 2;
if(intToSearch < sortedArray[mid])
upper = mid - 1;
else if (intToSearch > sortedArray[mid])
lower = mid + 1;
else
return mid;
}
return -1; // Returns -1 if no match is found
}
Following is a code sample extracted from here.
public class BinarySearch {
public boolean find(int[] sortedValues, int value) {
return search(sortedValues, value, 0, sortedValues.length - 1);
}
private boolean search(int[] sorted, int value, int leftIndex, int rightIndex) {
// 1. index check
if (leftIndex > rightIndex) {
return false;
}
// 2. middle index
int middle = (rightIndex + leftIndex) / 2;
// 3. recursive invoke
if (sorted[middle] > value) {
return search(sorted, value, leftIndex, middle - 1);
} else if (sorted[middle] < value) {
return search(sorted, value, middle + 1, rightIndex);
} else {
return true;
}
}
}
You can find implementations of the below test cases against the above binary search implementation as well in the reference link.
1. shouldReturnFalseIfArrayIsEmpty()
2. shouldReturnFalseIfNotFoundInSortedOddArray()
3. shouldReturnFalseIfNotFoundInSortedEvenArray()
4. shouldReturnTrueIfFoundAsFirstInSortedArray()
5. shouldReturnTrueIfFoundAtEndInSortedArray()
6. shouldReturnTrueIfFoundInMiddleInSortedArray()
7. shouldReturnTrueIfFoundAnywhereInSortedArray()
8. shouldReturnFalseIfNotFoundInSortedArray()
A possible example is :
// need extra "helper" method, feed in params
public int binarySearch(int[] a, int x) {
return binarySearch(a, x, 0, a.length - 1);
}
// need extra low and high parameters
private int binarySearch(int[ ] a, int x,
int low, int high) {
if (low > high) return -1;
int mid = (low + high)/2;
if (a[mid] == x) return mid;
else if (a[mid] < x)
return binarySearch(a, x, mid+1, high);
else // last possibility: a[mid] > x
return binarySearch(a, x, low, mid-1);
}
Here you can check in C Binary Search, With and Without Recursion
Source : http://www.cs.utsa.edu/~wagner/CS3343/recursion/binsearch.html
Here is a algorithm which should get you going. Let your method signature be:
public boolean binarysearchRecursion(Array, begin_index,end_index, search_element)
Check if your begin_index > end_index if YES then return false.
Calculate mid_element for your input array.
Check if your search_element is equal to this mid_element. if YES return true
If mid_element > search_element Call your method with for range 0 - mid
If mid_element < search_element Call your method with for range mid+1 - Length_of_Array
Also as #DwB said in his comment you are better using loop to get things done. Some problems are recursive in nature(Like binary tree problems). But this one is not one of them.
This is another way of doing recursion:
int[] n = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
#Test
public void testRecursiveSolution() {
Assert.assertEquals(0, recursiveBinarySearch(1,n));
Assert.assertEquals(15, recursiveBinarySearch(16,n));
Assert.assertEquals(14, recursiveBinarySearch(15,n));
Assert.assertEquals(13, recursiveBinarySearch(14,n));
Assert.assertEquals(12, recursiveBinarySearch(13,n));
Assert.assertEquals(11, recursiveBinarySearch(12,n));
Assert.assertEquals(10, recursiveBinarySearch(11,n));
Assert.assertEquals(9, recursiveBinarySearch(10,n));
Assert.assertEquals(-1, recursiveBinarySearch(100,n));
}
private int recursiveBinarySearch(int n, int[] array) {
if(array.length==1) {
if(array[0]==n) {
return 0;
} else {
return -1;
}
} else {
int mid = (array.length-1)/2;
if(array[mid]==n) {
return mid;
} else if(array[mid]>n) {
return recursiveBinarySearch(n, Arrays.copyOfRange(array, 0, mid));
} else {
int returnIndex = recursiveBinarySearch(n, Arrays.copyOfRange(array, mid+1, array.length));
if(returnIndex>=0) {
return returnIndex+mid+1;
} else {
return returnIndex;
}
}
}
}
While it doesn't return the index, this at least returns the idea of 'yes' or 'no' that something is in the collection:
public static boolean recursive(int[] input, int valueToFind) {
if (input.length == 0) {
return false;
}
int mid = input.length / 2;
if (input[mid] == valueToFind) {
return true;
} else if (input[mid] > valueToFind) {
int[] smallerInput = Arrays.copyOfRange(input, 0, mid);
return recursive(smallerInput, valueToFind);
} else if (input[mid] < valueToFind) {
int[] smallerInput = Arrays.copyOfRange(input, mid+1, input.length);
return recursive(smallerInput, valueToFind);
}
return false;
}
A recursion BinarySearch with break conditions in case you can not find the value you are looking for
public interface Searcher{
public int search(int [] data, int target, int low, int high);
}
The Implementation
public class BinarySearch implements Searcher {
public int search(int[] data, int target, int low, int high) {
//The return variable
int retorno = -1;
if(low > high) return retorno;
int middle = (high + low)/2;
if(target == data[middle]){
retorno = data[middle];
}else if(target < data[middle] && (middle - 1 != high)){
//the (middle - 1 != high) avoids beeing locked inside a never ending recursion loop
retorno = search(data, target, low, middle - 1);
}else if(target > data[middle] && (middle - 1 != low)){
//the (middle - 1 != low) avoids beeing locked inside a never ending recursion loop
retorno = search(data, target, middle - 1, high);
}else if(middle - 1 == low || middle - 1 == high){
//Break condition if you can not find the desired balue
retorno = -1;
}
return retorno;
}
}

Categories

Resources