[Instructions] [Search] [Current] [Changes] [Syllabus] [Handouts] [Outlines] [Labs] [Assignments] [Examples] [Bailey Docs] [SamR Docs] [Tutorial] [API]
Held: Friday, February 20, 1998
public List sort(List l)
{
if (l.empty()) {
return new List();
}
else {
Object smallest = l.deleteSmallest();
List sorted = sort(l);
sorted.prepend(smallest);
return sorted;
}
} // sort(List)
N!? It's N * (N-1)!
(N-1)!? It's (N-1) * (N-2)!
0!? It's 1.
public int factorial(int N)
throws Exception
{
if (n < 0) {
throw new Exception("Cannot take factorial of negative numbers.");
}
else if (n == 0) {
return 1;
}
else {
return n * factorial(n-1);
}
} // factorial
public returnType recursiveAlgorithm(someType input)
{
if (baseCase(input)) {
return baseComputation(input);
}
else {
return computation(input, recursiveAlgorithm(simplify(input)));
}
} // recursiveAlgorithm(someType)
time(N) which represents the running time on input of
N elements:
time(N) = c + time(N-1)
time(1) = c
/**
* Compute x^n for integers x and n
* pre: n >= 0
* pre: x > 0
* pre: x^n < maxint (can't really check this, but ...)
* post: returns x^n
*/
public int exp(int x, int n)
{
int result = 1; // The result, computed as we go
for(int i = 0; i < n; ++i) {
result *= x;
}
return result;
} // exp(int, int)
public int exp(int x, int n)
{
if (n == 0) return 1;
else {
return x * exp(x, n-1);
}
} // exp(int, int)
public int exp(int x, int n)
{
// Temporary value, used for integer calculations
int tmp;
// Choose what to do based on the exponent
if (n == 0) {
// x^0 = 1 for x != 0
return 1;
} // n is 0
else if (even(n)) {
// x^(2k) = x^k * x^k
tmp = exp(x, n/2);
return tmp*tmp;
} // n is even
else { // n is odd
// x^(k+1) = x * x^k
tmp = exp(x, n-1);
return x*tmp;
} // n is odd
} // exp
On to Design
Back to Algorithm Analysis, Continued
Outlines:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
Current position in syllabus
[Instructions] [Search] [Current] [Changes] [Syllabus] [Handouts] [Outlines] [Labs] [Assignments] [Examples] [Bailey Docs] [SamR Docs] [Tutorial] [API]
Disclaimer Often, these pages were created "on the fly" with little, if any, proofreading. Any or all of the information on the pages may be incorrect. Please contact me if you notice errors.
This page may be found at http://www.math.grin.edu/~rebelsky/Courses/CS152/98S/home/rebelsky/public_html/Courses/CS152/98S/Outlines/outline.20.html
Source text last modified Tue Jan 12 11:52:22 1999.
This page generated on Mon Jan 25 09:49:12 1999 by SiteWeaver. Validate this page.
Contact our webmaster at rebelsky@math.grin.edu