Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS 280 Data Structures Professor John Peterson. Homework Answers boolean m(int a[]) { for (int i = 0; i < a.length; i++) { for (int j = i+1; j < a.length;

Similar presentations


Presentation on theme: "CS 280 Data Structures Professor John Peterson. Homework Answers boolean m(int a[]) { for (int i = 0; i < a.length; i++) { for (int j = i+1; j < a.length;"— Presentation transcript:

1 CS 280 Data Structures Professor John Peterson

2 Homework Answers boolean m(int a[]) { for (int i = 0; i < a.length; i++) { for (int j = i+1; j < a.length; j++) { int s = 0; for (int k = j+1; k < a.length; k++) s = s + a[k]; if (a[i] + a[j] == s) return true; }}} return false; } Best case? Worst case?

3 Homework Answers boolean sumIn(int s, int a[]) { return (sumIn1(s,0,a)); } boolean sumIn1(int s, int which, int a[]) { if (which >= a.length) return (s == 0); if (sumIn1(s, which+1, a)) return true; if (sumIn1(s-a[which], which+1, a) return true; return false; } Best case? Worst case? General worst case data?

4 Heapsort Definition: a heap is a tree in which the heap condition holds at all points: heap(n) = a[n] >= a[left(n)] && a[n] >= a[right(n)] (this ignores the case where left / right are outside the heap – we could add a condition to catch this) This is essentially an invariant – something that we want to always be true.

5 Arrays as a Heap Suppose we have an array {4, 2, 7, 1, 3, 6, 9, 0, 5} Draw this as a tree. Is it a heap or not? 4 2 7 1 3 6 9 0 5

6 More Heaps How about these? What do these look like in array notation? 6 4 6 1 3 4 6 3 0 1 2 4 2 4

7 Creating a Heap We’ll start by turning a non-heap into a heap using exchanges. We’ll do this using recursion – a method which calls itself. Let’s start with a simple problem – a “headless” heap – one in which the heap condition holds everywhere except the root of the tree.

8 heapify 4 6 3 2 5 1 0 So – what should we do with the 4?

9 heapify 4 6 3 2 5 1 0 So – what should we do with the 4? Swap it with the larger of its two descendents. But that means that the subtree no longer satisfies the heap condition!

10 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 (right(i) < n) { if (s.gtr(l, i) || s.gtr(r, i)) { if (s.gtr(l,r)) { s.swap(i,l); heapify(l); } else { s.swap(i,r); heapify(r); }} else if (left(i) < n) { if (s.gtr(i,l)) swap(i,l); }


Download ppt "CS 280 Data Structures Professor John Peterson. Homework Answers boolean m(int a[]) { for (int i = 0; i < a.length; i++) { for (int j = i+1; j < a.length;"

Similar presentations


Ads by Google