רקורסיה
הוצג
15:34
חיפוש ומיון
ספר טלפונים עם מיליון שמות. אם תבדוק אותם אחד אחד, ייתכן שתבצע מיליון השוואות. אבל כבר ידוע לך הטריק: פתח אותו בחצי…
קריינות באנגלית · כתוביות באנגלית ובסינית 中文 שאפשר להחליף ביניהן
בשיעור הזה
| English | משמעות |
|---|---|
| recursive/rɪˈkɜːsɪv/ | רקורסיבי |
| loop/luːp/ | A structure that repeats a sequence of instructions. |
| base case/beɪs keɪs/ | מקרה בסיסי |
| recursive case/rɪˈkɜːsɪv keɪs/ | מקרה רקורסיבי |
| recursive call/rɪˈkɜːsɪv kɔːl/ | A function call made by the same function while it is running. |
| trace/treɪs/ | To follow an algorithm step by step and record its values. |
| call stack/kɔːl stæk/ | ערימת קריאות |
| recursion/rɪˈkɜːʃn/ | The use of a rule inside its own definition to express repetition. |
| function/ˈfʌŋkʃn/ | A mapping that assigns exactly one output to each allowed input. |
| Winding up | The stage when recursive calls are made until a base case is reached. |
| Unwinding | The stage when recursive calls return their results to the calls waiting for them. |
| stack/stæk/ | A last-in, first-out data structure in which items are added and removed at the same end. |
| parameters/pəˈræmɪtəz/ | Values that specify a model or function, or named inputs that a subroutine receives. |
| local variables/ˈləʊkl ˈveərɪəblz/ | A variable whose name is accessible only within a particular function, block or other limited scope. |
| stack frame/stæk freɪm/ | מסגרת ערימה |
| return address/rɪˈtɜːn əˈdres/ | The location where execution should resume after a called routine finishes, saved as part of managing the call. |
| pushed | Added to the top of the call stack when a function is called. |
| popped | Removed from the top of the call stack when a function returns. |
| ADT | A description of data and its allowed operations, separate from how it is stored. |
| memory/ˈmeməri/ | The part of a computer that holds data and programs currently in use. |
| stack overflow/stæk ˌəʊvəˈfləʊ/ | שפע ערימה |
| Deep recursion | Even a correct recursion of a million levels needs a million frames, so it can exhaust memory where a loop would use none. |
| Fibonacci | A sequence starting with zero and one, where each later number is the sum of the previous two. |
| memoisation/ˌmeməʊaɪˈzeɪʃn/ | ממוחזור |
| iteration/ˌɪtəˈreɪʃn/ | Repeating a sequence of instructions or calculations. |
| self-similar | Describes a problem that contains a smaller version of itself. |
| tree traversal | The process of visiting each node in a tree in a particular order. |
| divide and conquer/dɪˈvaɪd ænd ˈkɒŋkə/ | A method that divides a problem into smaller problems and combines their solutions. |
| binary search/ˈbaɪnəri sɜːtʃ/ | A search of ordered data that repeatedly compares with the middle item and discards half of the remaining search range. |
| merge sort/mɜːdʒ sɔːt/ | A sorting algorithm that divides data into smaller parts, sorts them, and joins them in order. |
| arithmetic overflow | A result that is too large or small for the available number of bits. |
| infinite recursion | When a function keeps calling itself because it never reaches a stopping point. |
הגדרה המכילה את עצמה
- איך אומרים מה הוא איל? ההורה שלך הוא איל. גם האיל של ההורה שלך הוא איל. שתי המשפטים הללו מגדירים שרשרת בלתי מוגבלת, והמשפט השני משתמש במילה שהוא מגדיר.
- זוהי לא ערעור מעגלי, משום שהמשפט הראשון מספק נקודת עצירה לשרשרת. ללא כך, ההגדרה הייתה מתפרקת לנצח.
- תוכניות יכולות להיכתב באותו אופן, ובמקרים שבהם הבעיה דומה לשרשרת זו, פתרון רקורסיבי קצר משמעותית ממלולך (loop).
- שיעור זה עוסק ב-מקרה הבסיס וב-מקרה הרקורסיבי, בעקבת צירוף רקורסיבי ובמה שמבצע ערמת הצירופים (call stack) בתחתית.

הכרטיס הזה תוקן, לכן הוא מוצג באנגלית עד שהתרגום שלו יעודכן.
The two cases
FUNCTION Factorial(n : INTEGER) RETURNS INTEGER
IF n = 0 OR n = 1 THEN
RETURN 1 // base case
ELSE
RETURN n * Factorial(n - 1) // recursive case
ENDIF
ENDFUNCTION
- The base case is a version of the problem small enough to answer directly, with no further call. It is what stops the recursion 递归.
- The recursive case calls the function 函数 again with a smaller input, moving towards the base case.
- Both are required. A terminating recursion needs a base case and recursive calls that make progress towards it.

Every recursive algorithm must have a base case because:
רמת קושי 1/5 · 100 מטבעות + בונוס קטן בהשלמה הראשונה היום
The base case is the condition that ends the chain of calls; without it the recursion runs forever.
Recursion is a natural fit for self-similar problems (trees, divide-and-conquer), but each call adds a stack frame — so without a base case it overflows the stack.
רמת קושי 1/5 · 100 מטבעות + בונוס קטן בהשלמה הראשונה היום
A simple counting loop is cleaner for plain iteration; recursion shines when the problem contains smaller copies of itself.
What must a recursive routine have to terminate? Select כולם that apply.
רמת קושי 2/5 · 140 מטבעות + בונוס קטן בהשלמה הראשונה היום
A base case alone is not enough: if the input never shrinks, the base case is never reached and frames pile up until the stack overflows.
דוגמה פתורה: עקיבת רקורסיה
- עקוב אחר
Factorial(4). - סיבוב:
Factorial(4)זקוק ל4 * Factorial(3), שזקוק ל3 * Factorial(2), שזקוק ל2 * Factorial(1). לא כופלו כלום עדיין; כל קריאה מחכה. - מקרה בסיס:
Factorial(1)מחזיר 1 ללא ביצוע צירופים נוספים. - פירוק:
2 * 1 = 2מחזיר ערך, ולאחר מכן3 * 2 = 6, ולאחר מכן4 * 6 = 24. - יש להציג את שני הכיוונים. עקבה שולכת רק למטה או רק חוזרת, מאבדת חצי מהנקודות.
Recursion unwinds from the leaves up
Step through fib(4) in the order the calls actually finish: the leaves (base cases) resolve first, then each parent combines its children. Notice fib(2) is computed twice — that repeated work is why naive recursion is slow.
What does Factorial(4) return?
רמת קושי 2/5 · 140 מטבעות + בונוס קטן בהשלמה הראשונה היום
4 × 3 × 2 × 1 = 24.
מה המכונה עושה
- לכל צירוף נדרשת העתכה משלו של הפרמטרים והמשתנים המקומיים שלו, מכיוון ש-
Factorial(3)ו-Factorial(2)הם צירופים שונים עם ערכים שונים שלn. - העותקים האלה חיים במסגרת סטוקה בסטוקת הקריאה: מסגרת אחת לכל קריאה בתהליך, המכילה את הפרמטרים, המשתנים המקומיים ואת כתובת ההחזרה.
- מסגרת נדחפת (pushed) בכל צירוף ומוסרת (popped) כאשר היא מחזירה ערך. זוהי הסיבה לכך שהערכים חוזרים בסדר הפוך לסדר הצירופים: ערכת הצירופים היא ערמה, בדיוק כמו ADT מהנושא 10.
Put the events of evaluating Factorial(4) in order.
רמת קושי 3/5 · 200 מטבעות + בונוס קטן בהשלמה הראשונה היום
Nothing is multiplied on the way down; every call waits. The multiplications all happen as the stack unwinds.
מה עלול לקלקל
- אין מקרה בסיס, או מקרה בסיס שמעולם לא מושג: הרקורסיה לעולם אינה נפסקת, הפריימים מצטברים והסטק של הקריאות מתמלא. זהו גלישת סטק.
- רקורסיה עמוקה: גם רקורסיה נכונה בעומק של מיליון רמות דורשת מיליון פריימים, ולכן יכולה לגרום לניצול זיכרון שבו לופ יתבצע ללא שימוש בזיכרון נוסף.
- עבודה חוזרת: אלגוריתם פיבונאצי רקורסיבי תמיטי מחשבב מחדש את אותם ערכים מספר פעמים אקספוננציאליות. ניתן לפתור זאת עם לופ, או עם זיכרון מעטפת (Memoisation), על ידי אחסון כל תוצאה בפעם הראשונה שהיא מחושבת.

Match each recursion term to what it means.
רמת קושי 2/5 · 140 מטבעות + בונוס קטן בהשלמה הראשונה היום
A recursion needs a base case to stop and a recursive case to shrink the problem; each call adds a stack frame.
A stack frame for a function call holds:
רמת קושי 1/5 · 100 מטבעות + בונוס קטן בהשלמה הראשונה היום
Each frame stores that call's parameters, locals and where to resume — so calls don't trample each other.
Each call in progress keeps its parameters and locals in its own ____ on the call stack.
רמת קושי 1/5 · 100 מטבעות + בונוס קטן בהשלמה הראשונה היום
Pushed on call, popped on return. That is why values come back in the reverse of the order the calls were made.
רקורסיה מול איטרציה
- רקורסיה מתאימה לבעיות חוזרות-עצמי, בהן הבעיה מכילה העתק קטן משלה: טרברסיה על עצים, גישת "חלק-וקה" כגון חיפוש בינארי ושייף מיזוג, והשרשרת האבות המוזכרת למעלה.
- איטרציה מתאימה לכל שאר המקרים, ואינה דורשת זיכרון נוסף עבור ההתחזרות.
- כל בעיה שניתן לפתור באמצעות רקורסיה ניתנת לפתרון באיטרציה, והדבר נכון גם להפך. הבחירה היא בין מה שמתאר את הבעיה בצורה ברורה יותר, לבין עלות הזיכרון של הסטק.

A recursive routine crashes with a stack overflow. Which explanation is correct?
רמת קושי 1/5 · 100 מטבעות + בונוס קטן בהשלמה הראשונה היום
Stack overflow is about frames, not arithmetic. A number too large for its register is an arithmetic overflow, a different thing entirely.
דוגמה מפורטת: ציינו את הסיכונים
- תלמיד כותב פונקציה רקורסיבית והיא קורסת בגלישת סטק. ציינו שתי סיבות אפשריות.
- אין מקרה בסיס, או שהמקרה הבסיסי לעולם לא מושג כי הקלט אינו הופך לקטן בכל קריאה, ולכן הקריאות ממשיכות לנצח והפריימים מצטברים.
- הרקורסיה נכונה אך עמוקה מדי: כל אחת מקריאות הרבות מאוד שומרת על פריימת הסטק שלה, והסטק של הקריאות מתמלא בזיכרון לפני שהמקרה הבסיסי מושג.
- שתי הסיבות עוסקות במצטברות פריימים. ציינו מה מצטבר ומדוע המצטבר הזה אינו מפסיק.
סימונים נופלים מהיד
- לרקורסיה דורשים שניהם: מקרה בסיס וקלט הופך לקטן. ציון מקרה בסיס בלבד הוא חצי מהתנאי.
- בטרייס, הדגימו את הקריאות מתקדמות ואת הערכים חוזרים. שני הכיוונים מובילים לציון.
- לכל קריאה יש פרמטרים ומשתנים מקומיים משלו בתוך פריימת סטק משלו. זוהי הסיבה לכך שרקורסיה דורשת זיכרון שאיטרציה אינה דורשת.
- גלישת סטק היא ספק בזיכרון הסטק עקב too many frames, ולא גלישה אריתמטית.
הבנתך מושלמת
- פונקציה רקורסיבית דורשת מקרה בסיס שפתור ישירות ומקרה רקורסיבי שמקרא את עצמו עם קלט קטן יותר
- לבצע טרייס בשני הכיוונים: קריאות מתקדמות למקרה הבסיס, ולאחר מכן ערכים חוזרים בחזרה
- לכל קריאה יש פריימת סטק משלה על סטק הקריאות, שנדחפת בקריאה ונשלפת בחזרה, דבר שמסביר מדוע רקורסיה דורשת זיכרון
- סיכונים: מקרה בסיס שאינו מושג גורם לרקורסיה אינסופית וגלישת סטק, רקורסיה עמוכה מזהרת זיכרון, ועבודה חוזרת דורשת לופ או זיכרון מעטפת
מה השתבש? רק צוות האתר רואה זאת.