Jaguar はコンセプトを非常にうまく表現しており、Paul は正確で詳細な説明を提供してくれました。これに追加するために、コードがどのように実行されるかを示す簡単な C コードを共有したいと思います。Jaguar が使用したのと同じ入力を使用したコードを次に示します。
#include<stdio.h>
int findMaxHelper(int A[], int left, int right){
int max1,max2;
int static tabcount;
int loop;
for(loop = 0 ; loop <tabcount;loop++) printf("\t");
tabcount++;
printf(" Entering: findMaxHelper(A, left = %d ,right = %d)\n\n",left,right);
if (left == right - 1){
for(loop = 0 ; loop <tabcount;loop++) printf("\t");
printf("\b\b\b\b\b\b\bLeaving: findMaxHelper(A, left = %d ,right = %d)| returning %d\n\n",left,right , A[left]);
tabcount--;
return A[left];
}
else
{
max1 = findMaxHelper(A, left, (right + left) / 2);
max2 = findMaxHelper(A, (right + left) / 2, right);
if (max1 > max2){
for(loop = 0 ; loop <tabcount;loop++) printf("\t");
printf("\b\b\b\b\b\b\bLeaving: findMaxHelper(A, left = %d ,right = %d) | returning max1=%d\n\n",left,right,max1);
tabcount--;
return max1;
}
else {
for(loop = 0 ; loop <tabcount;loop++) printf("\t");
printf("\b\b\b\b\b\b\bLeaving: findMaxHelper(A, left = %d ,right = %d)| returning max2=%d\n\n",left,right,max2);
tabcount--;
return max2;
}
}
}
int main (){
int A[] = { 34,3,47,91,32,0 };
int Ans =findMaxHelper(A,0,7);
printf( "And The Answer Is = %d \n",Ans);
}
Linuxマシンにコードをコピーして貼り付けることができます...おそらく、すべてのprintfの後にsleep(5)を配置して、再帰が実際にどのように機能するかを確認してください!...これが役立つことを願っています...ここで私のシステムからの出力も共有します:
Entering: findMaxHelper(A, left = 0 ,right = 7)
Entering: findMaxHelper(A, left = 0 ,right = 3)
Entering: findMaxHelper(A, left = 0 ,right = 1)
Leaving: findMaxHelper(A, left = 0 ,right = 1)| returning 34
Entering: findMaxHelper(A, left = 1 ,right = 3)
Entering: findMaxHelper(A, left = 1 ,right = 2)
Leaving: findMaxHelper(A, left = 1 ,right = 2)| returning 3
Entering: findMaxHelper(A, left = 2 ,right = 3)
Leaving: findMaxHelper(A, left = 2 ,right = 3)| returning 47
Leaving: findMaxHelper(A, left = 1 ,right = 3)| returning max2=47
Leaving: findMaxHelper(A, left = 0 ,right = 3)| returning max2=47
Entering: findMaxHelper(A, left = 3 ,right = 7)
Entering: findMaxHelper(A, left = 3 ,right = 5)
Entering: findMaxHelper(A, left = 3 ,right = 4)
Leaving: findMaxHelper(A, left = 3 ,right = 4)| returning 91
Entering: findMaxHelper(A, left = 4 ,right = 5)
Leaving: findMaxHelper(A, left = 4 ,right = 5)| returning 32
Leaving: findMaxHelper(A, left = 3 ,right = 5) | returning max1=91
Entering: findMaxHelper(A, left = 5 ,right = 7)
Entering: findMaxHelper(A, left = 5 ,right = 6)
Leaving: findMaxHelper(A, left = 5 ,right = 6)| returning 0
Entering: findMaxHelper(A, left = 6 ,right = 7)
Leaving: findMaxHelper(A, left = 6 ,right = 7)| returning 0
Leaving: findMaxHelper(A, left = 5 ,right = 7)| returning max2=0
Leaving: findMaxHelper(A, left = 3 ,right = 7) | returning max1=91
Leaving: findMaxHelper(A, left = 0 ,right = 7)| returning max2=91
And The Answer Is = 91