3.6.6 · HinglishSorting & Searching

Counting sort — O(n + k), integer keys only

2,039 words9 min readRead in English

3.6.6 · Coding › Sorting & Searching


YEH HAI KYA

Key vocabulary:

  • = sort kiye jaane wale elements ki sankhya.
  • = maximum key value (toh value range hai , jo values ka span hai).
  • Stable = equal keys apna original relative order maintain karte hain. Yeh tab matter karta hai jab hum records ko kisi integer field se sort karte hain.

KYUN yeh ko beat kar sakta hai

Jo cost hum pay karte hain: humhe size ka array chahiye. Agar bahut bada ho (jaise 64-bit keys), toh algorithm useless ho jaata hai. Chhota hi poori baat hai.


KAISE kaam karta hai — scratch se derive karo

Hum ek stable sort chahte hain. Positions ke baare mein reason karke algorithm build karte hain.

Step 1 — Count karo. Array count[0..k] banao, sab zeros. Input ek baar scan karo; key wale har element ke liye count[v] += 1 karo. Ab count[v] = kitni baar appear hota hai.

Yeh step kyun? Value ko place karne ke liye pehle jaanna zaroori hai ki kitne 's hain aur kitne values usse neeche hain.

Step 2 — Prefix sum (cumulative count). count[v] ko running total se replace karo. Ab count[v] = key wale elements ki sankhya.

Yeh step kyun? Agar elements ki key hai, toh key wala aakhri element output index (0-based) par hoga. Prefix sum exactly wahi boundary deta hai.

Step 3 — Place karo (input right-to-left scan karo). Har input element ke liye key ke saath (last se first ki taraf):

Right-to-left kyun? count[v]-1 value ke liye sabse upar wala free slot deta hai. Peeche se fill karte hue aur input ko peeche se scan karte hue, aakhri equal element aakhri slot mein jaata hai → original order preserve hoti hai → stable. Forward scan karna equal keys ko reverse kar deta.

Figure — Counting sort — O(n + k), integer keys only

Algorithm (pseudocode)

def counting_sort(A, k):          # keys in 0..k
    n = len(A)
    count = [0] * (k + 1)
    for x in A:                   # Step 1: tally
        count[key(x)] += 1
    for v in range(1, k + 1):     # Step 2: prefix sum
        count[v] += count[v - 1]
    out = [None] * n
    for x in reversed(A):         # Step 3: place, stably
        v = key(x)
        count[v] -= 1
        out[count[v]] = x
    return out

Worked examples


Common mistakes (steel-manned)


Flashcards

Counting sort ko bound beat karne wali assumption kya hai?
Keys chhote integers hain ek jaani-pehchaani range mein, directly array indices ki tarah use hote hain — koi comparisons nahi hote, isliye comparison lower bound apply nahi hota.
Counting sort ki time aur space complexity kya hai?
time aur space, jahan =elements ki sankhya, =max key value.
Prefix-sum step ke baad count[v] kya represent karta hai?
Key wale elements ki sankhya, yaani value ke block ke theek baad ki boundary index.
Placement ke dauran input right-to-left kyun scan karte hain?
Sort ko stable rakhne ke liye — aakhri equal element aakhri slot mein jaata hai, original relative order preserve hoti hai.
count ko size kyun karo, nahi?
Values tak range karti hain, jo distinct values hain.
Counting sort kab badly degrade hota hai?
Jab ho (jaise ya 32-bit keys) — space aur time tak blow up ho jaate hain.
Negative integer keys handle kaise karo?
Har key ko se offset karo taaki range par map ho jaaye, phir wapas jod do.
Counting sort ki stability practice mein kyun important hai?
Yeh counting sort ko radix sort ke andar stable per-digit pass ki tarah serve karne deti hai.

Recall Feynman: ek 12 saal ke bacche ko samjhao

Socho ek bade dhher ke exam papers score se sort karne hain, scores 0 se 10. Do papers ko ek baar mein compare karne ke bajaye, tum 11 boxes banate ho labeled 0–10 aur har paper apne box mein daal dete ho. Phir count karo: "Mere paas box 0 mein 3 papers hain, box 1 mein 5 hain..." Ek baar counts pata hone ke baad, tumhe pata hai box 0 ke papers slots 1–3 fill karenge, box 1 ke slots 4–8 fill karenge, aur aise hi — toh tum unhe ek pass mein perfect order mein rakh sakte ho. Tumne kabhi do scores compare nahi kiye; tumne sirf score ko address ki tarah use kiya. Yeh lightning fast hai kyunki scores chhote whole numbers hain. Agar scores koi bhi giant number ho sakte, tumhe ek billion boxes chahiye hote — useless.


Connections

  • Radix Sort — baar baar stable counting sort apply karta hai, ek digit at a time; isliye stability non-negotiable hai.
  • Bucket Sort — ek cousin jo buckets mein distribute karta hai, phir har bucket sort karta hai; counting sort iska special case hai jab har value ke liye ek slot ho.
  • Prefix Sum / Cumulative Array — woh engine jo counts ko positions mein convert karta hai.
  • Comparison Sort Lower Bound (Ω(n log n)) — woh barrier jise counting sort sidestep karta hai compare na karke.
  • Stability in Sorting — formal property jo yahan exploit ki gayi hai.
  • Time Complexity / Big-O — samajhne ke liye ki actually kab jeetta hai.

Concept Map

assumes

avoids

escapes

used as

beats

step 1

step 2

gives

step 3

ensures

costs

useless when

Counting Sort

Integer keys in 0 to k

Element comparisons

n log n lower bound

Array index O 1 access

Count occurrences

Prefix sum

Final positions

Place right to left

Stable order

O n plus k time and space

k very large