Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS 280 Data Structures Professor John Peterson. heapify void heapify(int i, Sortable s, int n) { // n is the limit of s int l = left(i); // 2*i+1 int.

Similar presentations


Presentation on theme: "CS 280 Data Structures Professor John Peterson. heapify void heapify(int i, Sortable s, int n) { // n is the limit of s int l = left(i); // 2*i+1 int."— Presentation transcript:

1 CS 280 Data Structures Professor John Peterson

2 heapify void heapify(int i, Sortable s, int n) { // n is the limit of s int l = left(i); // 2*i+1 int r = right(i); // 2*i+2 if (r < n) { if (s.gtr(l, i) || s.gtr(r, i)) { if (s.gtr(l,r)) { s.swap(i,l); heapify(l,s,n); } else { s.swap(i,r); heapify(r,s,n); }} else if (l < n) { if (s.gtr(i,l)) swap(i,l); }

3 Complexity What is the complexity of heapify(0, s, n)? Why? Let’s work some examples on the board.

4 Heapifying Everything Heapify has a basic problem: It assumes that left and right are already heapified. How can we get everything in the array heapified?????

5 Heapsort Stage 1 void heapsort(Sortable s) { n = s.size(); for (int i = n/2-1; i >= 0; i--) heapify(i, s.size()); ….. } Note that you could use n-1 instead of n/2-1 – this is just an optimization.

6 Anonymous Classes In the previous homework, we’ve seen a lot of boring classes – they have just one or two methods, no instance variables, and exist only to satisfy a particular interface. Rather than have to name something that we only use once, let’s look at anonymous classes. An anonymous class is indicated by “new InterfaceName”, followed by methods for that interface. Let’s work this out in NetBeans for the last homework.


Download ppt "CS 280 Data Structures Professor John Peterson. heapify void heapify(int i, Sortable s, int n) { // n is the limit of s int l = left(i); // 2*i+1 int."

Similar presentations


Ads by Google