



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!




They should be descending order by value per weight [value density] (or equivalently increasing by weight per value).
Base cases: Cmp(1) = Cmp(2^0 ) = 0 Cmp(2) = Cmp(2^1 ) = 1 Recurrence: Note: This portion (6 points) was discarded and converted to
Cmp(n>2) = Cmd ( n / 2 ) + Cmp ( n/2 ) + 2 — for general n Cmp(2k>1) = 2 * Cmd ( 2k–1) + 2 — for the restricted range of n = 2k
static int binSearch ( Comparable[] x, int n, Comparable val) { int lo = 0, hi = n-1;
{ int mid = (lo + hi) / 2; if (val.compareTo(x[mid]) > 0) lo = mid + 1; else hi = mid; } // end while if ( val.compareTo(x[hi]) > 0 ) // Belongs at the VERY end return n; else // Where val is (or belongs) return hi; } // end binSearch()
static int linSearch ( Object[] x, int n, Object val ) { int j; for ( j = 0; n > j; j++ ) if ( val.equals(x[j]) // Single statement, no braces return j; return -1; } // end linSearch()
public static void bubbleSort(Comparable[] a)
for (last = a.length-1;last>0;/no decrement/) { int mark = 0;// retain last swap position without changing last for (int k = 0; k < last; ++k) { if (a[k].compareTo(a[k+1]) > 0) { Comparable temp = a[k+1]; a[k+1] = a[k]; a[k] = temp; mark = k; //mark top of the swap } // end if } // end for last = mark; // update last } // end for } // end bubbleSort
public static long binom(int n, int k) { long answer = 1; // C(n-k, k-k) = C(n-k, 0) for (int ni = n-k+1, ki = 1; ki <= k ; ni++, ki++) answer = ( answer * ni ) / ki; return answer; } // end binom()
1, n, 2 n , n
, n
, √n, n
, n n , log 2 (n), n
log(n) 1, log 2 (n), √n, n, n
, n, n
log(n)
, n
, 2 n , n n
1 / 2 1 / 2 1 / 2 1 / 2 1
no 0/1 knapsack to obtain always the highest value for the knapsack’s capacity.
(^1) A note from calculus:
Also note: Derivative of logb
b ^ given logb(x) = ln(x)/ln(b) and the definition (^) x
1
Or, with regard to log 2 (n) and √n, you can go by the seat of your pants.