CS%20280%20Data%20Structures - PowerPoint PPT Presentation

About This Presentation
Title:

CS%20280%20Data%20Structures

Description:

CS 280. Data Structures. Professor John Peterson. Best / Worst Case. boolean m(int a ... Swap it with the larger of its two descendents. ... – PowerPoint PPT presentation

Number of Views:19
Avg rating:3.0/5.0
Slides: 11
Provided by: johnpe2
Learn more at: http://wiki.western.edu
Category:

less

Transcript and Presenter's Notes

Title: CS%20280%20Data%20Structures


1
CS 280Data Structures
  • Professor John Peterson

2
Best / Worst Case
  • boolean m(int a)
  • for (int i 0 i lt a.length i)
  • for (int j i1 j lt a.length j)
  • int s 0
  • for (int k j1 k lt a.length k)
  • s s ak
  • if (ai aj s)
  • return true
  • return false
  • Best case? Worst case?

3
Best / Worst Case
  • boolean sumIn(int s, int a)
  • return (sumIn1(s,0,a))
  • boolean sumIn1(int s, int which, int a)
  • if (which gt a.length) return (s 0)
  • if (sumIn1(s, which1, a)) return true
  • if (sumIn1(s-awhich, which1, 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) an gt aleft(n)
  • an gt aright(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
  • Well start by turning a non-heap into a heap
    using exchanges.
  • Well do this using recursion a method which
    calls itself.
  • Lets 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) // 2i1
  • int r right(i) // 2i2
  • if (right(i) lt 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) lt n)
  • if (s.gtr(i,l)) swap(i,l)
Write a Comment
User Comments (0)
About PowerShow.com