Docsity

Heapsort - Algorithms and Abstract Data Structures - Lecture Slides, Slides of Data Structures and Algorithms

Partial preview of the text

Download Heapsort - Algorithms and Abstract Data Structures - Lecture Slides and more Slides Data Structures and Algorithms in PDF only on Docsity!

CPSC 223

Algorithms & Data Abstract Structures

Lecture 16:

Heapsort

Today …

• Quiz 7

• Assignments

  • Assignment 7 due Thursday!

• Note on passing pointers by-reference

• Heapsort [Sect. 11.2]

• Heapsort exercise

CPSC 223 -­‐-­‐ Fall 2010 2

CPSC 223 -­‐-­‐ Fall 2010 3

Heapsort

Heapsort

  • The basic idea:
    • Build a heap out of the unsorted list
    • Create a temporary array
    • Find max value and delete
    • Put max value in last position of temp array
    • Find next max value and delete
    • Put next max value in the next to last position of temp array
    • Repeat until the heap is empty!
  • What is the cost of doing this?
    • O ( n log n ) for building the heap (repeated insertions)
    • O ( n log n ) for repeatedly deleting elements
    • So, O ( n log n ) CPSC 223 -­‐-­‐ Fall 2010 4

Heapsort

  • Building the Heap more efficiently CPSC 223 -­‐-­‐ Fall 2010 7 6 3 5 9 2 10 6 3 5 9 2 10 0 1 2 3 4 5 array = HeapRebuild (array, 6, 2); a semiheap 6 3 10 9 2 5 6 3 10 9 2 5 0 1 2 3 4 5 array =

Heapsort

  • Building the Heap more efficiently CPSC 223 -­‐-­‐ Fall 2010 8 6 3 10 9 2 5 6 3 10 9 2 5 0 1 2 3 4 5 array = HeapRebuild (array, 6, 1); a semiheap 6 9 10 3 2 5 6 9 10 3 2 5 0 1 2 3 4 5 array =

Heapsort

  • Building the Heap more efficiently CPSC 223 -­‐-­‐ Fall 2010 9 6 9 10 3 2 5 6 9 10 3 2 5 0 1 2 3 4 5 array = a semiheap HeapRebuild (array, 6, 0); 10 9 6 3 2 5 10 9 6 3 2 5 0 1 2 3 4 5 array =

Heapsort

  • Building the Heap more efficiently

// building the heap

for(int i = (size-­‐1)/2; i >= 0; i-­‐-­‐)

HeapRebuild (array, size, i);

CPSC 223 -­‐-­‐ Fall 2010 10

Heapsort

CPSC 223 -­‐-­‐ Fall 2010 13 void heapsort(int theArray[], int size) { for(int i = (size-1)/2; i >= 0; i--) // build heapRebuild(theArray, size, i); int last = size-1; for(int j = 1; j < size; j++) { // delete swap(theArray[0], theArray[last]); heapRebuild(theArray, last, 0); last--; } }

Comparison of Sorting Algorithms

CPSC 223 -­‐-­‐ Fall 2010 14 SelecSon Sort Bubble Sort Best Case Average Case Worst Case O ( n^2 ) O ( n^2 ) O ( n^2 ) O ( n ) O ( n^2 ) O ( n^2 ) InserSon Sort O ( n ) O ( n^2 ) O ( n^2 ) Quicksort O ( n log n ) O ( n log n ) O ( n^2 ) Treesort O ( n log n ) O ( n log n ) O ( n^2 ) Heapsort O ( n log n ) O ( n log n ) O ( n log n ) Mergesort O ( n log n ) O ( n log n ) O ( n log n )