To search for a smallest int in an array, I'm supposed to use a recursive method that actually divides the array into two pieces and find the smallest integer in each of the two pieces. The smallest integer of the entire array will be the smallest of those two integers. I have to use two indices, one starting from the beginning of the array and one starting from the end of the array. I wrote the method and I get ArrayIndexOutOfBoundsException when I compare the two small values of the halves. I am basing some of my coding off of this method, which divides up an array:
public static void displayArray(int array[], int first, int last)
{
if (first == last)
{
System.out.print(array[first] + " ");
}
else
{
int mid = (first + last)/2;
displayArray(array, first, mid);
displayArray(array, mid+1, last); }
}
}
In the method I'm coding, I think I have to stop the recursion when first = last, but how am I getting and index exception and how can I fix it?
Here is my code:
public static int minimum(int[] data, int first, int last)
{
int result = 0;
int middle;
int minOfFirstHalf;
int minOfSecondHalf;
if( first <0 || last <0 || first > last || data == null || data.length == 0 || (last > (data.length -1)))
{
throw new BadArgumentsForMinimumException("Invalid Input");
}
else if( data.length == 1)
{
result = data[0];
}
else
{
//this is where im having a problem
while(first !=last)
{
middle = (first + last)/ 2;
minimum( data, first, middle);
if( data[first] > data[middle])
{
minOfFirstHalf = data[middle];
}
else
{
minOfFirstHalf = data[first];
}
minimum(data, middle + 1, last);
if( data[middle + 1] > data[last])
{
minOfSecondHalf = data[last];
}
else
{
minOfSecondHalf = data[middle + 1];
}
if(data[minOfFirstHalf] == data[minOfSecondHalf]) //when i test this and it hits this part, I get the index exception
{
result = data[minOfSecondHalf];
}
else if(data[minOfFirstHalf] > data[minOfSecondHalf])
{
result = data[minOfSecondHalf];
}
else
{
result = data[minOfFirstHalf];
}
}
}
return result;
}