簡體   English   中英

我是否正確理解此遞歸?

[英]Am I correctly understanding this recursion?

有人可以幫我瀏覽我的遞歸代碼嗎? 這就是我的理解方式(但我認為我沒有正確地逐步執行代碼):

  1. if ( first > last ) return -1
  2. 其他
  3. if ( result == 0 ) return last
  4. else return SeqSearch (data, first, last-1, key)
  5. 重新啟動該方法,但lastlast-1 (“ keller”)
  6. 重復步驟1、2和3
  7. else return SeqSearch(data, first, last-1, key)
  8. 重新啟動方法,但lastlast-1 (“ six”)
  9. 等...

這是我的代碼:

public static void main (String[] args)
{
    String[] data = new String[]{"help","jackson","six","keller","mean"};
    int first = 0;
    int last = data.length-1;
    String key ="help";
    System.out.println(SeqSearch(data,first,last,key));
}
public static int SeqSearch(String[] data,int first,int last,String key)
{
    if(first > last)
        return -1;
    else{
        int result = data[last].compareTo(key);
        if(result == 0)
            return last;
        else
            return SeqSearch(data,first,last-1,key);
    }
}

理解遞歸函數的一個好方法是將其分解為基本案例和遞歸案例。

SeqSearch有兩種基本情況:

1.找不到

if (first > last)
    return -1;

2.發現價值

if (data[last].compareTo(key) == 0)
    return last;

現在,剩下了遞歸的情況。 在這里,我們只有一個遞歸的情況,但是可能有幾個。

現在,在設計遞歸函數時,必須確保每個遞歸調用都比以前的調用減少簡化 ,這意味着每次我們都接近一種基本情況。 這與歸納的數學概念非常相關。

因此,對遞歸案例的每次調用都必須比答案更近一步。 *在這里,我們看到last的值通過減去1來減小,在每一步將其接近零。

反過來,這意味着函數正在引用data數組中越來越小的子集。 從概念上講,這類似於將較小的數組傳遞給遞歸調用,該遞歸調用具有較少的元素。

至此,基本案例開始變得有意義了:

  1. first大於last ,我們有一個沒有元素的數組:列表的尾部超過了head

  2. 找到搜索鍵后,我們返回其索引作為結果。

此功能是特殊功能(在搜索功能中),因為它從列表的末尾查找第一個匹配的索引。 更常見的操作是從列表的開頭查找第一個匹配的索引。

這可以通過first遞增而不是last遞減來實現。 盡管遞歸步驟嚴格小於原始步驟,但這仍然算作減少-即使添加了-。


*這意味着每個遞歸調用都比上一個“簡單”; 因此,如果您可以隨時理解問題,則下一步應該更簡單; 唯一的麻煩是它嵌套在原始步驟中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM