3.4.13 · HinglishTrees

Heap sort — in-place, O(n log n)

1,795 words8 min readRead in English

3.4.13 · Coding › Trees


Heap (array mein) KYA hota hai?

Array kyun, pointers kyun nahi? Ek complete tree mein koi hole nahi hota — har level full hoti hai sivaaye possibly last level ke, jo left-to-right bhari jaati hai. Woh regular shape matlab hum child/parent positions arithmetic se calculate kar sakte hain, toh hume zero pointers aur zero extra memory chahiye. Yahi hai "in-place" ka raaz.

Recall Kyun

parent = (i-1)/2 hai? ka left child hai, right hai. Dono ko invert karo: se milta hai; se milta hai. ka integer floor division dono cases ko ek formula mein combine kar deta hai.


Algorithm KA KAAM (do phases)

Phase 1 — Heap banana (poore array ko heapify karna)

Ek unordered array ko max-heap mein badalna.

Phase 2 — Repeated extraction se sorting

Root (max) ko last heap slot se swap karo, heap ko ek se chhota karo, naye root ko neeche sift karo. Repeat karo.

Dono ke liye main engine hai sift-down (a.k.a. max_heapify).

Figure — Heap sort — in-place, O(n log n)
def sift_down(A, i, n):          # heap occupies A[0..n-1]
    while True:
        l, r = 2*i + 1, 2*i + 2
        largest = i
        if l < n and A[l] > A[largest]: largest = l
        if r < n and A[r] > A[largest]: largest = r
        if largest == i: break        # heap property restored
        A[i], A[largest] = A[largest], A[i]
        i = largest                   # follow the swap downward
 
def heap_sort(A):
    n = len(A)
    # Phase 1: build max-heap, bottom-up from last parent
    for i in range(n//2 - 1, -1, -1):
        sift_down(A, i, n)
    # Phase 2: extract max repeatedly
    for end in range(n - 1, 0, -1):
        A[0], A[end] = A[end], A[0]   # biggest -> sorted tail
        sift_down(A, 0, end)          # restore heap of size `end`

Time complexity ka derivation

Phase 2 hai — aasaan

Hum extractions karte hain, har ek size ke heap par sift-down hai:

Phase 1 (build) hai — surprising!

Naive guess: nodes = . Tight truth: zyaatar nodes bottom ke paas hote hain aur sift-down thoda hi karta hai.

Bottom se height par zyada se zyada nodes hote hain, har ek ka cost : Ab series evaluate karo. Maano . par: . Isliye


Worked examples


Common mistakes (steel-manned)


Flashcards

Heap sort time complexity (best, average, worst)
teeno cases mein.
Heap sort extra space
— fully in-place (iterative sift-down).
Kya heap sort stable hai?
Nahi — sifting swaps equal keys ka order bigaad dete hain.
Node (0-based) ke left child ka index
.
Node (0-based) ke parent ka index
.
Build-heap loop kahaan se shuru hoti hai?
Last internal node se, index , neeche 0 tak.
Build-heap kyun hai, kyun nahi?
Zyaatar nodes bottom ke paas hain; kyunki .
Sift-down ka precondition kya hai?
Node ke dono subtrees already valid heaps hain.
Phase 2 step ek line mein
Root ko last heap slot se swap karo, heap chhota karo, naye root ko sift-down karo.
Ascending sort ke liye max-heap vs min-heap?
Max-heap use karo; har round mein sabse bada end mein park hota hai.
Heap array mein store — pointers kyun nahi?
Yeh complete tree hai, toh child/parent positions pure index arithmetic se milti hain.
Recall Feynman: ek 12-saal ke bacche ko samjhao

Socho numbered cards ka ek pyramid hai, jisme rule hai ki har card apne neeche wale dono cards se bada hota hai. Toh sabse bada card hamesha upar hota hai. Unhe sort karne ke liye: sabse upar wala (sabse bada) card uthao aur apni row ke bilkul end mein rakh do. Ab ek chota card upar aa gaya aur rule toot gaya, toh use "sink" hone do — use neeche wale dono cards mein se bade wale se swap karte raho jab tak pyramid ka rule phir fix na ho jaaye. Ab naya top next-biggest hai; use last wale se thoda pehle park karo. Repeat karo jab tak pyramid khaali na ho — teri row sort ho gayi, aur tujhe iske liye koi doosri table nahi chahiye thi!

Connections

  • Binary Heap — woh data structure jis par heap sort run karta hai.
  • Priority Queue — same heap, repeated min/max access ke liye use hota hai.
  • Quicksort — yeh bhi in-place hai lekin worst case hai; heap sort guarantee karta hai.
  • Merge Sort aur stable hai, lekin extra space chahiye.
  • Complete Binary Tree — isliye index arithmetic kaam karta hai.
  • Big-O Notation — build-heap series analysis ke liye.
  • Introsort — hybrid jo quicksort ke worst case se bachne ke liye heap sort par fall back karta hai.

Concept Map

stored as

index arithmetic

enables

with heap property

restored by

used in

used in

bottom-up from n/2-1

swap root to tail

repeat n times

combined with

Complete binary tree

Flat array

parent and child positions

In-place, zero pointers

Max-heap: root is max

Sift-down / max_heapify

Phase 1: Build heap

Phase 2: Extract max

Sorted region grows right

O of n log n total