Units pass: [21,12,13,23]. Equal units preserve input order.
Week 08 · Lecture 9
Sorting limits and review
Explain the comparison-sorting lower bound and how restricted integer keys permit different methods. Review correctness, counts and data structures.
Read alongside the document
Use the lecture headings below in the English–Turkish notes. Document lecture numbers and course week numbers are different.
- Lecture 9: Linear Sorting
Warm-up: nuts and bolts; Can we sort faster than n log n?; Sorting without comparisons: playing cards; Bucketsort; When the assumption is wrong; Radix sort, and why the lower bound survives.
How can a linear-time sort coexist with an n log n lower bound?
Stable radix-sort [21,13,12,23] by units, then tens.
Tens pass: [12,13,21,23]. Equal tens preserve the units order established earlier.
Each stable counting pass costs O(n+b) for base b. With d digits the total is O(d(n+b)).
The Ω(n log n) worst-case lower bound concerns comparison-only sorting of arbitrary distinct keys. Radix sort uses key digits.
Change the case. The digit count and range matter. Calling radix sort O(n) without stating these assumptions is incomplete.
Explain before coding
State the input and required output. Trace a small example. Explain why each step is valid, count the work under a stated model, and test an edge case.
Python support for this week
Use // for integer quotient and % for remainder to isolate a digit. The main task is the paper trace.
values = [21, 13, 12, 23]
# sorted is stable; these lines demonstrate digit order,
# not a linear-time counting-sort implementation.
values = sorted(values, key=lambda x: x % 10)
print(values)
values = sorted(values, key=lambda x: x // 10)
print(values)Run this small demonstration after predicting its result. It illustrates the selected example; its input assumptions are part of the example.
Open the optional Python support library. Programming fluency is not required to complete the paper trace.
Read the related bilingual explanations here
Sections from the supplied lecture notes. Turkish paragraphs appear in red. Use this as a reference after the worked example.
Lecture 9 · Warm-up: nuts and bolts
Hazırlık: Somunlar ve cıvatalar
You have n bolts of different widths and the n matching nuts. You can test a nut against a bolt (too big, too small, or a fit), but you cannot compare two nuts or two bolts directly. Match them all.
Farklı genişliklerde n cıvatanız ve bunlarla eşleşen n somununuz var. Bir somunu bir cıvatada deneyebilirsiniz (çok büyük, çok küçük veya tam uyumlu), fakat iki somunu ya da iki cıvatayı doğrudan karşılaştıramazsınız. Hepsini eşleştirin.
O(n²): for each bolt, try every nut until one fits.
O(n²): Her cıvata için uygun somunu bulana kadar tüm somunları deneyin.
Smallest bolt and its nut in 2n − 2 tests: test the first bolt against every nut (n − 1 tests) while remembering the smallest nut that was still too small or the fit. Whichever nut comes out smallest belongs to the smallest bolt; find that bolt with n − 1 more tests.
En küçük cıvatayı ve somununu 2n − 2 denemede bulma: İlk cıvatayı her somunda deneyin (n − 1 deneme); hâlâ küçük kalan veya tam uyan somunların en küçüğünü aklınızda tutun. En küçük çıkan somun en küçük cıvataya aittir; o cıvatayı n − 1 ek denemeyle bulun.
Expected O(n log n): quicksort in disguise. Pick a random bolt as pivot and partition the nuts around it into “smaller”, “the match”, “larger”. The matching nut then partitions the bolts the same way. Recurse on both sides. It is exactly randomised quicksort, with nuts and bolts taking turns as pivots.
Beklenen O(n log n): Farklı bir görünüm altında hızlı sıralama. Rastgele bir cıvatayı pivot seçin ve somunları onun çevresinde “küçük”, “eşleşen”, “büyük” olarak bölümleyin. Ardından eşleşen somun, cıvataları aynı biçimde bölümler. İki tarafta da özyinelemeye devam edin. Bu, somunlarla cıvataların sırayla pivot olduğu rastgeleleştirilmiş hızlı sıralamanın aynısıdır.
Lecture 9 · Can we sort faster than n log n?
n log n’den daha hızlı sıralayabilir miyiz?
All the sorts so far (heapsort, mergesort, quicksort, insertion sort) are comparison-based: their only way to learn about the input is to ask “is x before y?”. Think of any such program as a decision tree. Each internal node is a comparison, with two branches for the two answers; each leaf is a final output, a particular reordering of the input. Running the program on a given input traces one path from the root to a leaf. For three items the tree starts with “a₁ < a₂?”, then “a₂ < a₃?” or “a₁ < a₃?”, and so on, down to leaves labelled with the six possible orders.
Şimdiye kadarki bütün sıralamalar (öbek, birleştirmeli, hızlı ve eklemeli sıralama) karşılaştırmaya dayalıdır: girdi hakkında bilgi edinmelerinin tek yolu “x, y’den önce mi gelir?” sorusudur. Böyle bir programı karar ağacı olarak düşünün. Her iç düğüm bir karşılaştırmadır ve iki yanıt için iki dalı vardır; her yaprak, girdinin belirli bir yeniden sıralanışı olan son çıktıdır. Programın belirli bir girdide çalıştırılması, kökten bir yaprağa giden yolu izler. Üç eleman için ağaç “a₁ < a₂?” ile başlar; ardından “a₂ < a₃?” veya “a₁ < a₃?” gelir ve olası altı sıralamayla etiketlenmiş yapraklara kadar sürer.
The height of this tree (the longest root-to-leaf path) is the number of comparisons in the worst case.
Bu ağacın yüksekliği (kökten yaprağa en uzun yol), en kötü durumdaki karşılaştırma sayısıdır.
The counting argument. Different input orders must lead to different outputs, so the tree needs at least one leaf per possible order: at least n! leaves. A binary tree of height h has at most 2ʰ leaves. Therefore
Sayma argümanı. Farklı girdi sıraları farklı çıktılara yol açmalıdır; dolayısıyla ağacın her olası sıra için en az bir yaprağa, yani en az n! yaprağa ihtiyacı vardır. Yüksekliği h olan ikili bir ağaç en fazla 2ʰ yaprak içerir. Bu nedenle:
How big is lg(n!)? The last n/2 factors of n! are each bigger than n/2, so n! > (n/2)^(n/2) and
lg(n!) ne kadar büyüktür? n! içindeki son n/2 çarpanın her biri n/2’den büyüktür; dolayısıyla n! > (n/2)^(n/2) ve
Stirling’s approximation gives the sharper n! > (n/e)ⁿ, hence h ≥ n lg n − n lg e = Ω(n log n). Either way: any comparison-based sort needs Ω(n log n) comparisons in the worst case, so mergesort and heapsort are optimal up to constants. This is the course’s first lower bound, a statement about every possible algorithm rather than one particular algorithm.
Stirling yaklaşımı daha sıkı olan n! > (n/e)ⁿ eşitsizliğini verir; buradan h ≥ n lg n − n lg e = Ω(n log n) elde edilir. Her iki yolla da sonuç aynıdır: karşılaştırmaya dayalı her sıralama, en kötü durumda Ω(n log n) karşılaştırma gerektirir. Dolayısıyla birleştirmeli ve öbek sıralaması, sabit çarpanlar dışında optimaldir. Bu, dersin ilk alt sınırıdır: belirli bir algoritma hakkında değil, olası bütün algoritmalar hakkında bir önermedir.
Lecture 9 · Sorting without comparisons: playing cards
Karşılaştırmasız sıralama: İskambil kartları
How would you sort a shuffled deck of cards? Not by comparing pairs. You would lay out 13 piles, one per rank, drop each card onto its pile, tidy the few cards in each pile by suit, and stack the piles up. If finding the right pile takes O(1) and each pile holds O(1) cards, the whole thing takes O(n). The trick is that dropping a card onto “the 7 pile” uses the value of the card directly, which is more information than a yes/no comparison gives.
Karıştırılmış bir iskambil destesini nasıl sıralarsınız? Çiftleri karşılaştırarak değil. Her kart değeri için bir tane olmak üzere 13 yığın oluşturur, her kartı kendi yığınına koyar, her yığındaki birkaç kartı türlerine göre düzenler ve yığınları üst üste toplarsınız. Doğru yığını bulmak O(1) sürüyor ve her yığın O(1) kart tutuyorsa işlemin tamamı O(n) sürer. Buradaki püf noktası, bir kartı “7’ler yığınına” bırakmanın kartın değerini doğrudan kullanmasıdır; bu, evet/hayır karşılaştırmasının sağladığından daha fazla bilgi verir.
Lecture 9 · Bucketsort
Kova sıralaması (bucketsort)
Suppose we sort n numbers drawn from 1 to m, and we know they are spread roughly evenly over that range. Set up n buckets, bucket i covering the interval of numbers from (i − 1)m/n + 1 to i·m/n. A number x goes into bucket ⌈xn/m⌉, which is a single arithmetic operation, O(1). Then sort each bucket (with anything, even insertion sort) and concatenate the buckets in order.
1 ile m arasında seçilmiş n sayıyı sıraladığımızı ve bu aralığa yaklaşık eşit dağıldıklarını bildiğimizi varsayın. n kova oluşturun; i. kova, (i − 1)m/n + 1 ile i·m/n arasındaki sayıları kapsasın. x sayısı ⌈xn/m⌉ kovasına gider; bu tek bir aritmetik işlem, yani O(1)’dir. Ardından her kovayı (herhangi bir yöntemle, eklemeli sıralamayla bile) sıralayın ve kovaları sırayla art arda ekleyin.
With evenly spread keys the expected number of items per bucket is 1, so sorting each bucket is O(1), and the total for bucketing, sorting and concatenating is O(n).
Anahtarlar eşit dağıldığında kova başına beklenen eleman sayısı 1’dir; dolayısıyla her kovayı sıralamak O(1), kovalara dağıtma, sıralama ve birleştirme işlemlerinin toplamı O(n)’dir.
What happened to the Ω(n log n) lower bound? Nothing: bucketsort is not comparison-based, so the bound does not apply to it. But it bought linear time with an assumption about the data.
Ω(n log n) alt sınırına ne oldu? Hiçbir şey: kova sıralaması karşılaştırmaya dayalı değildir; dolayısıyla sınır ona uygulanmaz. Ancak doğrusal zamanı, veri hakkında bir varsayım karşılığında elde etmiştir.
Lecture 9 · When the assumption is wrong
Varsayım yanlış olduğunda
If the data is not evenly spread, all the items may land in one or two buckets. We spend linear time distributing them and learn nothing; sorting the one big bucket is the whole original problem again. This is precisely why the course insists on worst-case analysis: the “expected” case is only as good as the assumption behind it.
Veri eşit dağılmıyorsa bütün elemanlar bir veya iki kovaya düşebilir. Elemanları dağıtmak için doğrusal zaman harcar ve hiçbir şey öğrenemeyiz; tek büyük kovayı sıralamak, başlangıçtaki problemin aynısıdır. Dersin en kötü durum analizinde ısrar etmesinin nedeni tam olarak budur: “beklenen” durum, ancak arkasındaki varsayım kadar iyidir.
Skiena’s example is a phone book. Are there many Skienas? No. Many Smiths? Yes. Many Shiffletts? In Charlottesville, Virginia, the Shifflett family fills pages of the directory (the slide shows the columns), while the 1,000-page Manhattan directory has seven. Real-world distributions are lumpy in ways you cannot predict from the name alone. Either understand your data’s distribution, or use an algorithm with a good worst-case or randomised guarantee.
Skiena’nın örneği bir telefon rehberidir. Çok sayıda Skiena var mı? Hayır. Çok sayıda Smith? Evet. Peki Shifflett? Virginia’nın Charlottesville kentinde Shifflett ailesi rehberin sayfalarını doldurur (slayt bu sütunları gösterir), oysa 1,000 sayfalık Manhattan rehberinde yedi tane vardır. Gerçek dünyadaki dağılımlar, yalnızca isme bakılarak öngörülemeyecek biçimde kümelenir. Ya verinizin dağılımını anlayın ya da en kötü durum veya rastgeleleştirilmiş performans garantisi iyi olan bir algoritma kullanın.
Lecture 9 · Radix sort, and why the lower bound survives
Basamak sıralaması ve alt sınırın neden geçerliliğini koruduğu
Radix sort sorts strings (or numbers viewed as digit strings) by bucketing on the last character, then re-bucketing on the second-to-last while preserving the order from the previous pass, and so on to the first character. Ties are broken by the earlier passes. Sorting n strings of length m takes O(nm), which is linear in the total size of the input.
Basamak sıralaması, dizeleri (veya rakam dizeleri olarak görülen sayıları) son karakterlerine göre kovalara dağıtır; ardından önceki geçişin sırasını koruyarak sondan ikinci karaktere göre yeniden dağıtır ve ilk karaktere kadar sürdürür. Eşitlikler önceki geçişlerle çözülür. Uzunluğu m olan n dizeyi sıralamak O(nm) sürer; bu, girdinin toplam boyutunda doğrusaldır.
Does this beat the bound? No. For n keys to be distinct they need at least lg n characters each (otherwise there are not enough different strings), so m must be Ω(log n), and O(nm) is O(n log n) again. Sorting n arbitrary distinct keys cannot be done faster than Θ(n log n); linear-time sorts win only by exploiting structure that arbitrary keys do not have.
Bu, sınırın altına iner mi? Hayır. n anahtarın farklı olabilmesi için her birinin en az lg n karaktere ihtiyacı vardır (aksi hâlde yeterince farklı dize yoktur). Dolayısıyla m, Ω(log n) olmalıdır ve O(nm) yeniden O(n log n) olur. Keyfî n farklı anahtarı Θ(n log n)’den daha hızlı sıralamak mümkün değildir; doğrusal zamanlı sıralamalar ancak keyfî anahtarlarda bulunmayan bir yapıdan yararlanarak üstünlük sağlar.
Begin with the easy tests and the worked example. Remaining questions provide repeated teaching practice; hard questions are optional depth. Some tests revisit earlier prerequisites. Answers stay visible.
Practice with answers
10 test questions · 6 written questions · 16 total
Each question is followed by its answer and explanation. Hard questions also include a starting hint and smaller reasoning steps.
Test questions
Choose one option. Cost questions state their model and whether the bound is tight, expected or worst-case. Here lg means log₂, and heap positions start at 1.
Question 1 · easy
Which statement about 5n² + 3n is TRUE?
Answer: option C. n³ is a valid, if loose, upper bound; the tight bound is Θ(n²).
Question 2 · easy
Which is the strongest valid lower bound listed for worst-case comparison sorting of n distinct keys?
Answer: option B. The decision tree needs n! leaves, so height at least lg(n!).
Question 3 · easy
In least-significant-digit-first radix sort, each digit pass must be:
Answer: option A. Ties on the current digit must keep the order established by earlier passes.
Question 4 · easy · course question
Stable sorting preserves:
Answer: option B. Stability matters when earlier ordering information must survive another sorting pass.
Question 5 · medium
Which pair of constants proves 3n² + 10n = O(n²)?
Answer: option B. 3n² + 10n ≤ 4n² exactly when n ≥ 10. (a) never holds, (c) never holds, and (d) fails at n = 1.
Question 6 · medium
Which function eventually grows fastest as n tends to infinity?
Answer: option B. An exponential dominates every polynomial, however high its degree.
Question 7 · medium
Using Θ(n) buckets and insertion sort within each bucket, which distribution assumption gives expected O(n) bucket-sort time?
Answer: option B. Independent uniform keys give bounded expected bucket occupancy and O(n) expected total local-sorting work. It is not a worst-case linear guarantee for arbitrary keys.
Question 8 · medium
Radix sort is run on 170, 45, 75, 90, 802, 24. After the first pass (on the units digit) the order is:
Answer: option A. Units digits 0, 0, 2, 4, 5, 5; the stable pass keeps 170 before 90 and 45 before 75.
Question 9 · hard · optional challenge
Which statement is FALSE?
In simpler words: Compare eventual growth, not values at one small input.
Starting hint: Any fixed positive power of n eventually beats any fixed power of log n.
Answer: option C. Any positive power of n, including √n, dominates every power of log n.
Step by step
- Option (c) reverses this rule: (log n)²/√n tends to zero.
- The other comparisons follow the ladder: logarithms, powers, exponentials, then factorials.
Question 10 · hard · optional challenge
For n ≥ 2, sort n integers in [0, n³ − 1] using word-RAM radix sort in base n. How many stable counting-sort passes suffice for O(n) total time?
In simpler words: Count digits in base n instead of base ten.
Starting hint: The biggest allowed integer is just below n³.
Answer: option C. Each number has three base-n digits, and each pass is a linear-time stable bucket sort.
Step by step
- Write x=d₂n²+d₁n+d₀, with each digit in 0,…,n−1.
- Three stable counting-sort passes handle d₀, d₁, d₂. Each costs O(n+n), so the total is O(n).
Written questions
Read each question together with its explanation, trace or proof. Numbering continues from the test questions.
Question 11 · easy
Bucketsort can run in O(n). Why does that not contradict the Ω(n log n) lower bound?
Answer & reasoning
the bound applies to comparison-based sorting only. Bucketsort uses the numeric value of a key to pick its bucket directly, which is not a comparison, and it relies on an assumption about the distribution of the keys.
Question 12 · medium
Buckets numbered 1–10 cover 1–10, 11–20, …, 91–100. Which bucket contains 37? What happens if all ten values lie between 91 and 100?
Answer & reasoning
37 goes into bucket 4. Values 91–100 all go into bucket 10. Insertion-sorting one crowded bucket can take Θ(n²) work in the worst case. Expected linear bucket sorting needs an appropriate distribution assumption and a linear number of buckets; it is not a guarantee for arbitrary inputs.
Question 13 · medium
Radix-sort 329, 457, 657, 839, 436, 720, 355 by units, then tens, then hundreds. Show the order after each pass.
Answer & reasoning
after the units pass (stable): 720, 355, 436, 457, 657, 329, 839. After the tens pass: 720, 329, 436, 839, 355, 457, 657. After the hundreds pass: 329, 355, 436, 457, 657, 720, 839. Each pass must be stable so earlier passes break ties.
Question 14 · medium
How many comparisons does any algorithm need in the worst case to sort 3 items? Can that bound be achieved?
Answer & reasoning
the decision tree needs at least 3! = 6 leaves, and a tree of height 2 has at most 4, so some input needs at least 3 comparisons. Three do suffice: compare a and b, compare the larger with c, and one more comparison places the remaining element.
Question 15 · hard · optional challenge
Prove that lg(n!) = Θ(n log n).
In simpler words: Trap the logarithm of n! between two n log n expressions.
Starting hint: For the lower bound, keep only the largest half of the factors.
Answer & reasoning
Step by step
- Upper bound: each of the n factors is at most n, so n! ≤ nⁿ.
- Lower bound: at least n/2 factors are at least n/2, so n! ≥ (n/2)^(n/2), ignoring harmless integer rounding.
- Taking logs gives (n/2)log₂(n/2) ≤ log₂(n!) ≤ n log₂ n. Both sides grow as n log n.
upper bound: n! ≤ nⁿ, so lg(n!) ≤ n lg n. Lower bound: the largest n/2 factors of n! are each at least n/2, so n! ≥ (n/2)^(n/2) and lg(n!) ≥ (n/2) lg(n/2) = (n/2)(lg n − 1), which is Ω(n log n). Together, Θ(n log n).
Question 16 · hard · optional challenge
Sort n integers, each between 0 and n² − 1, in O(n) time.
In simpler words: Sort bounded integers using two digits instead of pairwise comparisons.
Starting hint: Write x as high·n + low.
Answer & reasoning
Step by step
- For 0 ≤ x < n², high = floor(x/n) and low = x mod n, each in 0,…,n−1.
- Stable counting sort first by low, then by high. Stability preserves the low-digit order within a high-digit tie.
- Each pass scans n items and n counters: O(n). Two passes remain O(n), assuming the integers fit in a constant number of machine words.
write each number in base n; it has exactly two digits, each between 0 and n − 1. Radix sort with two passes, each a stable bucket sort into n buckets, costs O(n) per pass. Comparison sorting would need Ω(n log n); the trick is that the keys are bounded.