So for my homework, I was supposed to design an algorithm which was divide-and-conquer that fulfilled the task of finding the two smallest numbers in an array of size n.
I recognize that my version is a bit cheap in that regard, in that it uses reference variables and only does work on the size 1 cases of the recursion. Is this still technically considered divide-and-conquer? Or is it practically too close to a linear search. If it is divide-and-conquer, how could you express the recurrence relation when the work is being done only on the "leaves" of the recursion.
find_mins(int A[], int& min, int& sec_min, int l, int r){
int pivot = (l+r)/2;
if(l==r){
if(A[l] < min){
sec_min = min;
min = A[l];
return;
}
else if(A[l] < sec_min && A[l] > min){
sec_min = A[l];
return;
}
return;
}
find_mins(A,min,sec_min,1,pivot);
find_mins(A,min,sec_min,pivot+1,r);
}
"Pseudocode"
FUNCTION(Array, min1, min2, left, right)
Find pivot
if(size of subproblem is 1)
calculate mins
function(Array,min1,min2,1, pivot)
function(array,min1,min2,pivot+1,right)
Keep in mind, the code really isn't all that relevant, I just am curious if the structure fits divide-and-conquer description. My concern is that because work is only being done on the case where the size is 1, that it's more of a "linear search" than anything else.
min
to be too small from the start, so thatA[l] < min
is never true - in that case you will just getmin
back instead of the smallest element in array. Also, what if all numbers in array are the same, or if there are two same numbers, which also happen to be the minimum? As for your original question: D&C is more like a height of an angel, it doesn't really have a rigorous definition, it's more of a folklore. I could recognize the intention in your code, others would do too, I guess. $\endgroup$