140 likes | 242 Vues
Lab 4. 9/29. main { x=5; y=4; z=8; ... f(x,y,z); }. System Stack. f(int a, int b, int c) { g(a+b+c); }. g(int n) { ... }. main { x=5; y=4; z=8; ... f(x,y,z); }. System Stack. f(int a, int b, int c) { g(a+b+c); }. Main X = 5
E N D
Lab 4 9/29
main { x=5; y=4; z=8; ... f(x,y,z); } System Stack f(int a, int b, int c) { g(a+b+c); } g(int n) { ... }
main { x=5; y=4; z=8; ... f(x,y,z); } System Stack f(int a, int b, int c) { g(a+b+c); } Main X = 5 Y = 4 Z = 8 g(int n) { ... }
main { x=5; y=4; z=8; ... f(x,y,z); } System Stack f A = 5 B = 4 C = 8 f(int a, int b, int c) { g(a+b+c); } Main X = 5 Y = 4 Z = 8 g(int n) { ... }
main { x=5; y=4; z=8; ... f(x,y,z); } System Stack g N = 17 f A = 5 B = 4 C = 8 f(int a, int b, int c) { g(a+b+c); } Main X = 5 Y = 4 Z = 8 g(int n) { ... }
main { x=5; y=4; z=8; ... f(x,y,z); } System Stack g N = 17 f A = 5 B = 4 C = 8 f(int a, int b, int c) { g(a+b+c); } Main X = 5 Y = 4 Z = 8 g(int n) { ... }
main { x=5; y=4; z=8; ... f(x,y,z); } System Stack g N = 17 f A = 5 B = 4 C = 8 f(int a, int b, int c) { g(a+b+c); } Main X = 5 Y = 4 Z = 8 g(int n) { ... }
Recursive Function • Factorial: • 1! = 1 • n! = n(n-1)! • Fibonacci • fib(1) = 1 • fib(2) = 1 • fib(n) = fib(1) + fib(2)
Recursive Call fact(int n) { if (n == 1) { return 1; else { return (n * fact(n-1)); } } Fact N = 4
Recursive Call fact(int n) { if (n == 1) { return 1; else { return (n * fact(n-1)); } } Fact N = 1 Fact N = 2 Fact N = 3 Fact N = 4
Recursive Call fact(int n) { if (n == 1) { return 1; else { return (n * fact(n-1)); } } Fact N = 1 1 Fact N = 2 2 Fact N = 3 6 Fact N = 4 24
HeapSort • What is a heap? • “Almost complete” Binary tree • n levels • first n-1 levels are complete • nth level (the leaves) are all compacted towards the left. • Size n heap can be stored in a size n array. • Usually you can’t store a size n tree in a size n array... • Because the “shape” or connectivity of the tree can be different for different data. • But there is only one shape for a size n heap • So you only need to explicitly store the data.
Heapsort Templates • Templates posted: • HeapSort.java • Main program with input/output, etc. • You could use this file as is • Heap.java • A superclass for MinHeap and MaxHeap • MinHeap • A class to hold a heap with the minimum at the top. • (What we have discussed in lab) • MaxHeap • A class to hold a heap with the maximum at the top. • (The opposite of what we have discussed in lab).
HeapSort Templates • Min and Max heap have some methods with no body– these need to be completed by you to use these templates. • add and deleteRoot • These are where the “sorting work” happens. • There are also some things in Heap.java that need to be completed. • parent, leftChild, rightChild • (Not the abstract methods add and deleteRoot! These are to be implemented in MinHeap and MaxHeap!) • http://home.gwu.edu/~bhosp/cs151.html