Sometimes we don't have to solve all subproblems to get our solution. Let's consider an example.
Mark is a physicist, and he needs to measure some radius using a meter scale during an experiment. Accidentally, he has measured the first few objects using a centimeter scale. Now, the measured data looks like this: . Mark has to divide the first few data points (that are greater than 100) by 100. He has written this pseudocode using the divide and conquer paradigm to automate this job:
function update_radius(radius, start, end):
if start == end - 1 then:
radius[start] = radius[start] / 100
return radius[start:end]
if start < end then:
mid = int((start + end) div 2)
if radius[mid] < 100 then:
left = update_radius(radius, start, mid)
right = radius[mid:end]
else:
left = update_radius(radius, start, mid)
right = update_radius(radius, mid, end)
return combine(left, right)
Here function returns the largest integer less than the given number, i.e. for example, will return 4. The returns a subarray of the array from the index up to the index but excluding the index . The function combines the elements of two arrays into a single array.
If you examine Mark's pseudocode, you will notice that he hasn't used any recursion for the subproblem if the first element of the right subarray is less than 100. Often, this kind of observation of data will improve the performance of our programs.
Now suppose one of Mark's students has some measurement data for the same experiment in the following array: . Clearly, the student has messed up with the measuring scales randomly. Can you use Mark's pseudocode to help the student correct the data?