Data Journey

International Studies Grad. racing for AI Engineer

Download as .zip Download as .tar.gz View on GitHub
16 January 2021

Heap Sort

by mervyn

Heap Sort

Analysis of Heap Sort

\(lg(n!)\) and \(nlg(n)\)

A plot of \(lg(n!)\) and \(nlg(n)\) suggests that they are asymptotically related:

lg!

In-place Implementation

max

inplace

Additionally, because arrays start at 0 (we started at entry 1 for binary heaps), we need different formulas for the children and parent.

Can we convert this complete tree into a max-heap?

Let’s work bottom-up: each leaf node is a max heap on its own

Analysis of Heapify

Considering a perfect tree of height h:

heapify

At depth k, there are \(2^k\) nodes and in the worst case, all of these nodes would have to percolated down h-k levels

Writing this sum mathematically, we get: \(\sum_{k=0}^{h}2^{k}(h-k)=(2^{h+1}-1)-(h+1)\)

Recall that for a perfect tree, \(n=2^h+1-1\) and \(h+1=lg(n+1)\), therefore \(\sum_{k=0}^{h}2^{k}(h-k)=n-lg(n+1)\)

Each swap requires two comparisons (which child is greatest), so there is a maximum of \(2n\) (or \(\Theta(n)\)) comparisons

Example: Heap Sort

Convert unordered array with n=10 elements into a max-heap [46 52 28 17 3 63 34 81 70 95] None of the leaf nodes need to be percolated down, and the first non-leaf node is position \(n/2\)

  1. Compare 3 with its child and swap them
  2. Compare 17 with its two children and swap it with the maximum child (70) …
  3. Converted the unsorted array into a max-heap [95 81 63 70 52 28 34 17 46 3]

heapifyarr

  1. Pop the maximum element of this heap: gap at the back of the array
  2. Fill the last entry in the array with the largest element
  3. Repeat this process: pop the maximum element, and then insert it at the end of the array (pop and append)

Summary

heapsum

source “K-MOOC 허재필 교수님의 <인공지능을 위한 알고리즘과 자료구조: 이론, 코딩, 그리고 컴퓨팅 사고> 강좌의 10-1 힙 정렬 중(http://www.kmooc.kr/courses/course-v1:SKKUk+SKKU_46+2020_T1)”

back next

tags:

Comments

Post comment
Loading...

Share this: