# Recursivley Find A Max Number in an Array

**807601**Feb 20, 2008 1:12 PM

Hello everyone,

My goal: Given an array of numbers, I want to recursively use

given: array = { 1, 9, 2, 3, 1, 7, 6, 4 };

int maxNumIndex = max_index(array, leftIndex, rightIndex);

maxNumIndex would be 1.

Here is what I have so far, and I'm not sure if this is the right way to go about doing this. I figure I need to compare the number at the MaxIndex, see if that is > or <, then set the maxNumberIndex equal to whatever the MaxIndex was.

This is what I have (remember I'm using

My goal: Given an array of numbers, I want to recursively use

**Divide & Conquer method**, search that array for the biggest number in it, and then return the**index**of that number. Ex:given: array = { 1, 9, 2, 3, 1, 7, 6, 4 };

int maxNumIndex = max_index(array, leftIndex, rightIndex);

maxNumIndex would be 1.

Here is what I have so far, and I'm not sure if this is the right way to go about doing this. I figure I need to compare the number at the MaxIndex, see if that is > or <, then set the maxNumberIndex equal to whatever the MaxIndex was.

This is what I have (remember I'm using

**Divide & Conquer**):```
// Return the max num's index using divide and conquer
//args being passed in: a = the array, lf = left Index, rt = the right Index.
private static int max_index(int a[], int lf, int rt)
{
int maxNumberIndex;
int mid = (rt + lf) / 2;
maxNumberIndex = a[mid];
int rightMaxIndex = max_index(a, mid + 1, rt);
int leftMaxIndex = max_index(a, lf, mid - 1);
if (lf == rt)
{
maxNumberIndex = lf;
}
else if ((a[leftMaxIndex] > a[rightMaxIndex]) && (a[leftMaxIndex] > a[mid]))
{
maxNumberIndex = leftMaxIndex;
}
else if ((a[rightMaxIndex] > a[leftMaxIndex]) && (a[rightMaxIndex] > a[mid]))
{
maxNumberIndex = rightMaxIndex;
}
if ((a[mid] > a[leftMaxIndex]) && (a[mid] > a[rightMaxIndex]))
{
maxNumberIndex = mid;
}
else if ((a[mid] == a[rightMaxIndex]) && (a[leftMaxIndex] == a[rightMaxIndex]))
{
maxNumberIndex = mid;
}
return maxNumberIndex; //RETURN OUR MAX NUMBER INDEX
}
```

Thoughts? - 7 Views
- Tags: none (add)