###MaxMin Theorem - A divide and conquer approach
- The variables
minimum_of_this_scope
will be holding the minimum value in the scope[first_index, last_index]
, i.e. the minimum out of{ array[first_index], array[first_index+1], .. , array[last_index] }
- Similarly,
maximum_of_this_scope
will be holding the maximum value in the scope. - Although they are being passed as an arguement, they will be making use of pass by reference to store the maximum/minimum values. We have two values and hence simple
return
will not be working.
MAXMIN(array, first_index, last_index, minimum_of_this_scope, maximum_of_this_scope):
IF first_index == last_index:
/* We are looking at a scope with single element only. */
minimum_of_this_scope = maximum_of_this_scope = array[first_index]
ELSE IF last_index - first_index == 1:
/* A scope with two elements. The smaller one will be the minimum and the other will be maximum. */
IF array[first_index] > array[last_index]:
minimum_of_this_scope = array[last_index]
maximum_of_this_scope = array[first_index]
ELSE
minimum_of_this_scope = array[first_index]
maximum_of_this_scope = array[last_index]
END IF
ELSE
/* There's more element. Divide the scopes into smaller ones */
middle_index = FLOOR[(first_index + last_index)/2]
max_min(array, first_index, middle_index, minimum_from_half1, maximum_from_half1)
max_min(array, middle_index + 1, last_index, minimum_from_half2, maximum_from_half2)
/* Compare the results from smaller halves and then assign the maximum and minimum for this scope. */
IF minimum_from_half1 < minimum_from_half2:
minimum_of_this_scope = minimum_from_half1
ELSE
minimum_of_this_scope = minimum_from_half2
END IF
IF maximum_from_half1 > maximum_from_half2:
maximum_of_this_scope = maximum_from_half1
ELSE
maximum_of_this_scope = maximum_from_half2
END IF
END IF
END MAXMIN
For zero based indexing, the method should be called with MAXMIN(array, 0, size - 1, &minimum, &maximum)
References of the variables(maximum
& minimum
) are used and hence after completion, they will be containig the desired result.
Generally if we are making use of linear comparison, it will take
2n
comparisons to compute bothminimum
andmaximum
together, while this way the number of comparisons are reduced to3n/2 - 2
. If we are talking about time complexity, they both are winded up to O(n), but the divide and conquer approach will make lesser comparison than the linear one.