java - How do I find a recurrence relation for a recursive method? -
so i'm trying find recurrence relation java method:
public static pair min/max(int start, int end, int[] a) { int mid; pair pair = new pair(a[start], a[end]); pair p1; pair p2; if (start == end) { //if n = 1 return pair; } else if (end == start + 1) { //if n = 2 if (a[start] > a[end]) { pair.upper = a[end]; pair.lower = a[start]; } else { pair.upper = a[start]; pair.lower = a[end]; } return pair; } mid = (end + start) / 2; //if n > 2 p1 = min/max(end, mid, a); p2 = min/max(mid + 1, ub, a); if (p1.lower < p2.lower) pair.upper = p1.lower; else pair.lower = p2.lower; if (p1.upper > p2.upper) pair.upper = p1.upper; else pair.upper = p2.upper; return pair; //the min , max pair }
this supposed find max , min of array using ⌈3n/2 - 2⌉ comparisons. uses class:
class pair { int lower; int upper; pair ( int a, int o ) { lower = a; upper = o; } }
so recurrence relation method? know starts out as:
c(n) = 0 if n=1 1 if n=2
and i'm trying figure out equation when n > 2. first off above method run in ⌈3n/2 - 2⌉ comparisons. i'm wondering because of line mid = (lb + ub) / 2
makes me think i'm still splitting array ⌈n/2⌉ , ⌊n/2⌋ parts not me ⌈3n/2 - 2⌉ comparisons each time. know there better way same thing code i'm writing has use recursion.
update: after adding counter statements find above code not use ⌈3n/2 - 2⌉ comparisons every array. think problem variable mid. mid i'm supposed split array don't think i'm splitting correctly have proper number of comparisons.
let n = end - start + 1
. presume mean recurrence expressing number of comparisons.
in general case doing 4 comparisons each level of recursion , splitting list in half. recurrence is:
t(n) = 4 + t( floor(n/2) ) + t( ceiling(n/2) ) n > 1
nb: seem have begun lb
, ub
, switched partially start
, end
.
Comments
Post a Comment