CS 280
Data Structures
Professor John Peterson
Homework / Project
Note the homework isn’t due till
tomorrow. Plus it’s not too hard.
The project IS due Friday though.
What’s Wrong?
public class SortByName<T> { … }
public class GtrStdNum implements
Comparable<Integer> { … }
public class Sort<T> implements Comparable<T> {
…}
public class SortNumber<Integer> implements
Comparable {
public boolean gtr(Integer x, Integer y)
return x.studentNumber > y.studentNumber
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.
Statics
Understanding how and when to use statics is a
really tough part of Java.
What situations does it make sense in to use
static variables? Static final variables? A
class with only static methods?
What is special about static vars/methods?
What are the rules of a static method?
Let’s look at how to store sort functions into
statics.
Project 4
Let’s take a look.
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); }}} // Missing } in old slide
else if (l < n) {
if (s.gtr(l,i)) swap(i,l); } // Bug in old slide
Heapsort Stage 1
void heapsort(Sortable s) {
n = s.size();
for (int i = n/2-1; i >= 0; i--)
heapify(i, s, n);
…..
}
Note that you could use n-1 instead of
n/2-1 – this is just an optimization.
Complexity of Stage 1
So what’s the complexity of this?
Stage 2
If we have the entire array heapified,
then what next?
Swap the top element with the last
element (where it belongs). Then make
the array “one shorter” and re-heapify.
That is, keep taking the big thing at the
front and moving it to the back.
Stage 2 Code
for (int i = s.size()-1, i > 0; i--) {
swap(0,i);
heapify(0, s, i); }
Invariants
What invariants do we have in the two
stages of the sort?
Complexity
What is the best case complexity?
Worst case? Is this stable? Online?
© Copyright 2026 Paperzz