-3

Given an unsorted array find the max and min values. I'm trying to do this in a recursive, divide and conquer way but I keep getting a stack overflow error. I debugged and i keep getting the error in my recursive calls but do not know what is wrong or how to fix it.

I do have static min and max variables.

Thanks for the information and help!

static void findMaxMin(int[] array, int start, int end)
{
    if (end == 2)
    {
        setMaxMin(array);
    }
    else
    {
        int mid = ((end) / 2);
        findMaxMin(array, start, mid);
        findMaxMin(array, mid + 1, end);
    }
}
private static void setMaxMin(int[] array)
{
    if (array[0] > array[1])
    {
        max = array[0];
        min = array[1];
    }
    else
    {
        min = array[0];
        max = array[1];
    }
}
Bidou
  • 7,378
  • 9
  • 47
  • 70
md05062
  • 3
  • 2
  • 6

1 Answers1

0

Here is one simple way to do it (without recursion):

void FindMinAndMaxValues(int[] array out int min, out int max)
{
    min = int.MaxValue,
    max = int.MinValue;

    foreach(var val in array)
    {
        max = (val > max) ? val : max;
        min = (val < min) ? val : min;
    }
}

Please note that I'm using out parameters here. This is done for simplicity of the code. Usually, I would prefer to either return a designated class or a tuple.

Also, LINQ has min and max extension methods that you can use - so the entire thing turns to something like this:

var max = array.Max();
var min = array.Min();
Zohar Peled
  • 79,642
  • 10
  • 69
  • 121