你的算法有点搞砸了。例如,greatest<arr[start]
永远不会是真的,因为您只需设置greatest = arr[start]
。这里有一个评价工作的算法:
#include <stdio.h>
int max(int arr[], int start, int end)
{
if (start >= end) {
/* Shouldn't get here, but return 0 if we do */
return 0;
}
else if (end - start == 1) {
/* Only one element, so it's the maximum by definiton */
return arr[start];
}
else {
/* Find the maximum of the rest of the list... */
int greatest = max(arr, start + 1, end);
/* ...and return the greater of it, and the first element */
return arr[start] > greatest ? arr[start] : greatest;
}
}
int main(void)
{
int arr[] = { 8, 1, 2, 3, 12, 5, 6, 7, 8, 9 };
int start = 0;
int end = 10;
int greatest = max(arr, start, end);
printf("%d\n", greatest);
}
与输出:
[email protected]:~/src/sandbox$ ./max
12
[email protected]:~/src/sandbox$
让我们通过它与一个简单的列表,{1,5,3}。每个缩进级别表示您的递归函数调用之一。每次我们看到max()
,我们都会上升到一个水平 - 每当我们看到return
时,我们就会回到一个水平。
In main(), int greatest = max(list, 0, 3)
In call 1: (end - start == 1) is false
In call 1: int greatest = max(list, 1, 3)
In call 2: (end - start == 1) is false
In call 2: int greatest = max(list, 2, 3)
In call 3: (end - start == 1) is true
In call 3: return arr[2], which is 3
Back in call 2: greatest now equals 3
Back in call 2: arr[1] == 5, which is > 3, so return arr[1], which is 5
Back in call 1: greatest now equals 5
Back in call 1: arr[0] == 1, which is not > 5, so return greatest, which is 5
Back in main(), greatest now equals 5
记住,每次你看到int greatest
时间,这是一个的正在创建不同变量。他们都有相同的名字,但由于他们都在不同的范围内,他们仍然是不同的。例如,呼叫2中的int greatest
与呼叫1中的int greatest
完全分开,正如呼叫1中的int greatest
与main()
中的int greatest
完全分开。
编辑:从评论,如果你想最大值的指数为好,这会做到这一点:
#include <stdio.h>
int max_index(int arr[], int start, int end)
{
if (start >= end) {
return 0;
}
else if (end - start == 1) {
return start;
}
else {
int greatest = max_index(arr, start + 1, end);
return arr[start] > arr[greatest] ? start : greatest;
}
}
int max(int arr[], int start, int end)
{
if (start >= end) {
/* Shouldn't get here, but return 0 if we do */
return 0;
}
else if (end - start == 1) {
/* Only one element, so it's the maximum by definiton */
return arr[start];
}
else {
/* Find the maximum of the rest of the list... */
int greatest = max(arr, start + 1, end);
/* ...and return the greater of it, and the first element */
return arr[start] > greatest ? arr[start] : greatest;
}
}
int main(void)
{
int arr[] = { 8, 1, 2, 3, 12, 5, 6, 7, 8, 9 };
int start = 0;
int end = 10;
int greatest = max(arr, start, end);
int index = max_index(arr, start, end);
printf("Greatest value is %d at index %d\n", greatest, index);
}
输出:
[email protected]:~/src/sandbox$ ./max
Greatest value is 12 at index 4
[email protected]:~/src/sandbox$
你需要复制 - 和 - 将*精确*代码粘贴到问题中。通过重新输入它,你已经引入了一个错字('printf'的'pintf')。我们无法猜测您的问题中的代码与您询问的代码之间可能存在哪些其他差异。 – 2014-10-20 14:54:17