public static int fact int n return factaccn
רקורסיית זנב : חישוב עצרת public static int fact (int n){ return factacc(n, 1); } public static int factacc (int n, int acc){ int ans; if (n==0) ans = acc; else ans = factacc(n-1, n*acc); return ans; } 2
היפוך מחרוזת public static String reverse(String s){ String answer; if (s. length()==0) answer = s; else answer = reverse(s. substring(1)) + s. char. At(0); return answer; } 3
היפוך מחרוזת – רקורסיית זנב public static String reverse(String s) { return reverse(s, ""); } public static String reverse(String s, String acc){ String answer; if (s. length()==0) answer = acc; else answer = reverse(s. substring(1), s. char. At(0)+acc); return answer; } 4
מציאת אינדקס האיבר המינימלי public static int rec. Find. Min(int [] array, int i){ // finds the index of the minimal value in "array" // from "i" (inclusive) till array. length. // assumes that: "i" is in the range of the index. int ans = i; if (i<array. length-1) { int j = rec. Find. Min(array, i+1); if (array[j]<array[i]) ans = j; else ans = i; } return ans; } 5
חיפוש בינארי public static int binary. Search(int e, int[] a){ int from = 0, till = a. length-1; int ans = -1; while (from <= till & ans==-1){ int mid = (from + till)/2; if (e < a[mid]) till = mid-1; else if (e > a[mid]) from = mid+1; else ans = mid; } return ans; } 7
חיפוש בינארי רקורסיבי public static int rec. Search(int e, int[] arr) { return rec. Search(e, arr, 0, arr. length-1); } 8
חיפוש בינארי רקורסיבי public static int rec. Search(int e, int[] a, int from, int till){ int ans = -1; if (from <= till) { int mid = (from + till)/2; if (e < a[mid]) ans = rec. Search(e, a, from, mid-1); else if (e > a[mid]) ans = rec. Search(e, a, mid+1, till); else ans = mid; } return ans; } 9
קוד - מגדלי הנוי public static void hanoi(int n, char source, char destination, char extra) { if (n > 0) { hanoi(n-1, source, extra, destination); System. out. println("Move disk from "+source+ " to "+destination); hanoi(n-1, extra, destination, source); } } 12
( מגדלי הנוי )דוגמת הרצה Move disk from a to c Move disk from a to b Move disk from c to b Move disk from a to c Move disk from b to a Move disk from b to c Move disk from a to c 13
מיון בחירה public static void selection. Sort (int[] arr) { int to = arr. length; for(int from=0; from<to-1; from=from+1) { int min. Ind = rec. Find. Min(arr, from); swap(arr, from, min. Ind); } } 14
רקורסיבי - מיון בחירה public static void rec. Sel. Sort(int[] array){ sel. Sort(array, 0); } public static void sel. Sort(int[] array, int i){ // sort array from i (till i is sorted and min) if (i<array. length){ swap(array, i, min. Index(array, i)); sel. Sort(array, i+1); } } 15
- Slides: 16