你的算法有點搞砸了。例如,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