awelgorithms

Build a heap from values

Updated

Copy the values into an array, then restore min-heap order (n inserts or build-heap). Input order is not heap order.

What to focus on

After the build, a[0] is the minimum and every parent index beats its children. [9, 4, 1] must become a heap, not stay as written.

Worked examples

already a heap

a = [1, 4, 9]
  1. order already holds
  2. a[0] is 1

Result: [1, 4, 9]

needs restore

a = [9, 4, 1]
  1. last parent i=0
  2. swap 9 with 1

Result: [1, 4, 9]

one value

a = [7]
  1. copy 7
  2. no restore

Result: [7]

Try it

Write buildHeap(a). a is the input array. Last parent is Math.floor(n/2)-1. parent(i) = Math.floor((i-1)/2). Heapify uses left 2*i+1 and right 2*i+2. Restore min-heap order in place. Return a. Print a. Check a[0] is the min. [1, 4, 9] stays [9, 4, 1] → [1, 4, 9] [7] stays [7]

a is a non-empty array of 1–6 integers. Restore min-heap order in place. Last parent is Math.floor(n/2)-1.