-2
我正在做一項任務,在這裏得到了我需要的一段代碼的幫助。程序工作正常,但只有一部分我不明白。在這個recusion程序中的這段代碼發生了什麼?
public class largest_in_array
{
public static void main(String[] args)
{
int array [] = {23,35,67,76,34};
System.out.println("The largest number in the array is: ");
System.out.println(array[largest(array, 0, 0)]);
}
public static int largest(int array[], int maxIndex, int i)
{
int ans = 0;
if(i == array.length-1)
{
ans = maxIndex;
}
else
{
ans = largest(array, (Math.max(array[maxIndex], array[i]) == array[maxIndex]) ? maxIndex : i, ++i);
}
return ans;
}
}
我不明白的部分是這樣的:
ans = largest(array, (Math.max(array[maxIndex], array[i]) == array[maxIndex]) ? maxIndex : i, ++i);
似乎maxIndex開始爲0,然後圍繞第三遞歸步驟它獲得價值1。我不知道這是怎麼發生的,因爲maxIndex似乎永遠不會在代碼中的任何地方增加。
我很抱歉,如果我的問題是事先混淆。任何解釋將不勝感激。
首先感謝您回覆如此迅速。 其次,我很抱歉,但我仍然沒有看到它從0增加maxIndex的位置。 我看到「i」得到遞增,但maxIndex僅在相等的語句爲真(對我的不正確理解)被添加到它。 – Lyhnmyu 2014-11-23 19:27:36
我加了一個很長的解釋,希望有幫助。即使你的代碼沒有理由遞歸,並且如果它是以迭代方式編寫的話,會更容易理解。理解遞歸過程中發生的事情仍然很好。 – fishinear 2014-11-23 19:59:08
非常感謝你。我現在明白了一點 – Lyhnmyu 2014-11-24 03:24:43