-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsorting.html
More file actions
1492 lines (1258 loc) · 89.2 KB
/
sorting.html
File metadata and controls
1492 lines (1258 loc) · 89.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sorting & Searching | DSA - Better Dev</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<link rel="stylesheet" href="style.css">
</head>
<body>
<header class="topbar">
<button class="sidebar-toggle" aria-label="Open navigation" aria-expanded="false">
<span class="hamburger-icon"></span>
</button>
<a href="index.html" class="logo">Better Dev</a>
</header>
<div class="sidebar-backdrop" aria-hidden="true"></div>
<aside class="sidebar" aria-label="Site navigation">
<div class="sidebar-header">
<span class="sidebar-title">Navigation</span>
<button class="sidebar-close" aria-label="Close navigation">×</button>
</div>
<div class="sidebar-search">
<input type="text" class="sidebar-search-input" placeholder="Search topics..." aria-label="Search topics">
<div class="sidebar-search-results"></div>
</div>
<nav class="sidebar-nav">
<div class="sidebar-group">
<a href="index.html">Home</a>
</div>
<div class="sidebar-group">
<div class="sidebar-group-label">Mathematics</div>
<a href="pre-algebra.html">Pre-Algebra</a>
<a href="algebra.html">Algebra</a>
<a href="sequences-series.html">Sequences & Series</a>
<a href="geometry.html">Geometry</a>
<a href="calculus.html">Calculus</a>
<a href="discrete-math.html">Discrete Math</a>
<a href="linear-algebra.html">Linear Algebra</a>
<a href="probability.html">Probability & Statistics</a>
<a href="binary-systems.html">Binary & Number Systems</a>
<a href="number-theory.html">Number Theory for CP</a>
<a href="computational-geometry.html">Computational Geometry</a>
<a href="game-theory.html">Game Theory</a>
</div>
<div class="sidebar-group">
<div class="sidebar-group-label">Data Structures & Algorithms</div>
<a href="dsa-foundations.html">DSA Foundations</a>
<a href="arrays.html">Arrays & Strings</a>
<a href="stacks-queues.html">Stacks & Queues</a>
<a href="hashmaps.html">Hash Maps & Sets</a>
<a href="linked-lists.html">Linked Lists</a>
<a href="trees.html">Trees & BST</a>
<a href="graphs.html">Graphs</a>
<a href="sorting.html">Sorting & Searching</a>
<a href="patterns.html">LeetCode Patterns</a>
<a href="dp.html">Dynamic Programming</a>
<a href="advanced.html">Advanced Topics</a>
<a href="string-algorithms.html">String Algorithms</a>
<a href="advanced-graphs.html">Advanced Graphs</a>
<a href="advanced-dp.html">Advanced DP</a>
<a href="advanced-ds.html">Advanced Data Structures</a>
<a href="leetcode-650.html">The 650 Problems</a>
<a href="competitive-programming.html">CP Roadmap</a>
</div>
<div class="sidebar-group">
<div class="sidebar-group-label">Languages & Systems</div>
<a href="cpp.html">C++</a>
<a href="golang.html">Go</a>
<a href="javascript.html">JavaScript Deep Dive</a>
<a href="typescript.html">TypeScript</a>
<a href="nodejs.html">Node.js Internals</a>
<a href="os.html">Operating Systems</a>
<a href="linux.html">Linux</a>
<a href="git.html">Git</a>
<a href="backend.html">Backend</a>
<a href="system-design.html">System Design</a>
<a href="networking.html">Networking</a>
<a href="cloud.html">Cloud & Infrastructure</a>
<a href="docker.html">Docker & Compose</a>
<a href="kubernetes.html">Kubernetes</a>
<a href="message-queues.html">Queues & Pub/Sub</a>
<a href="selfhosting.html">VPS & Self-Hosting</a>
<a href="databases.html">PostgreSQL & MySQL</a>
<a href="stripe.html">Stripe & Payments</a>
<a href="distributed-systems.html">Distributed Systems</a>
<a href="backend-engineering.html">Backend Engineering</a>
</div>
<div class="sidebar-group">
<div class="sidebar-group-label">JS/TS Ecosystem</div>
<a href="js-tooling.html">Tooling & Bundlers</a>
<a href="js-testing.html">Testing</a>
<a href="ts-projects.html">Building with TS</a>
</div>
<div class="sidebar-group">
<div class="sidebar-group-label">More</div>
<a href="seans-brain.html">Sean's Brain</a>
</div>
</nav>
</aside>
<div class="container">
<!-- Page Header -->
<div class="page-header">
<div class="breadcrumb"><a href="index.html">Home</a> / Sorting & Searching</div>
<h1>Sorting & Searching</h1>
<p>From O(n²) basics to O(n log n) workhorses and binary search. Know the trade-offs, write the code, crush the interviews.</p>
</div>
<!-- Table of Contents -->
<div class="toc">
<h4>Table of Contents</h4>
<a href="#why-sorting">1. Why Sorting Matters</a>
<a href="#comparison">2. Comparison of All Sorting Algorithms</a>
<a href="#bubble-sort">3. Bubble Sort</a>
<a href="#selection-sort">4. Selection Sort</a>
<a href="#insertion-sort">5. Insertion Sort</a>
<a href="#merge-sort">6. Merge Sort</a>
<a href="#quick-sort">7. Quick Sort</a>
<a href="#heap-sort">8. Heap Sort</a>
<a href="#counting-radix">9. Counting Sort & Radix Sort</a>
<a href="#binary-search">10. Binary Search</a>
<a href="#built-in">11. Built-in Sorting</a>
<a href="#leetcode">12. LeetCode Problems</a>
<a href="#quiz">13. Practice Quiz</a>
</div>
<!-- ============================== -->
<!-- 1. WHY SORTING MATTERS -->
<!-- ============================== -->
<section id="why-sorting">
<h2>1. Why Sorting Matters</h2>
<p>Sorting is one of the most fundamental operations in computer science. Nearly every system you interact with uses sorting under the hood -- databases order query results, search engines rank pages, and operating systems schedule processes.</p>
<ul>
<li><strong>Binary search requires sorted data.</strong> You cannot binary search an unsorted array. Sorting first gives you O(n log n + log n) = O(n log n) total, which beats O(n) linear search when you query multiple times.</li>
<li><strong>Sorting makes problems easier.</strong> Two-pointer techniques, deduplication, finding closest pairs, merge intervals -- all of these become straightforward once the data is sorted.</li>
<li><strong>Understanding trade-offs is key.</strong> There is no single "best" sorting algorithm. The right choice depends on data size, whether it is nearly sorted, memory constraints, and stability requirements.</li>
</ul>
<div class="tip-box">
<div class="label">Tip</div>
<p>In interviews, you rarely need to implement a sorting algorithm from scratch. But you absolutely need to know their complexities, trade-offs, and when to use each one. For binary search, you need to be able to write it cold.</p>
</div>
</section>
<!-- ============================== -->
<!-- 2. COMPARISON TABLE -->
<!-- ============================== -->
<section id="comparison">
<h2>2. Comparison of All Sorting Algorithms</h2>
<div style="overflow-x: auto;">
<table>
<thead>
<tr>
<th>Algorithm</th>
<th>Best</th>
<th>Average</th>
<th>Worst</th>
<th>Space</th>
<th>Stable?</th>
</tr>
</thead>
<tbody>
<tr>
<td>Bubble Sort</td>
<td>O(n)</td>
<td>O(n²)</td>
<td>O(n²)</td>
<td>O(1)</td>
<td>Yes</td>
</tr>
<tr>
<td>Selection Sort</td>
<td>O(n²)</td>
<td>O(n²)</td>
<td>O(n²)</td>
<td>O(1)</td>
<td>No</td>
</tr>
<tr>
<td>Insertion Sort</td>
<td>O(n)</td>
<td>O(n²)</td>
<td>O(n²)</td>
<td>O(1)</td>
<td>Yes</td>
</tr>
<tr>
<td>Merge Sort</td>
<td>O(n log n)</td>
<td>O(n log n)</td>
<td>O(n log n)</td>
<td>O(n)</td>
<td>Yes</td>
</tr>
<tr>
<td>Quick Sort</td>
<td>O(n log n)</td>
<td>O(n log n)</td>
<td>O(n²)</td>
<td>O(log n)</td>
<td>No</td>
</tr>
<tr>
<td>Heap Sort</td>
<td>O(n log n)</td>
<td>O(n log n)</td>
<td>O(n log n)</td>
<td>O(1)</td>
<td>No</td>
</tr>
<tr>
<td>Counting Sort</td>
<td>O(n + k)</td>
<td>O(n + k)</td>
<td>O(n + k)</td>
<td>O(k)</td>
<td>Yes</td>
</tr>
<tr>
<td>Radix Sort</td>
<td>O(nk)</td>
<td>O(nk)</td>
<td>O(nk)</td>
<td>O(n + k)</td>
<td>Yes</td>
</tr>
</tbody>
</table>
</div>
<h3>What Does "Stable" Mean?</h3>
<p>A sorting algorithm is <strong>stable</strong> if it preserves the relative order of elements that have equal keys. For example, if you sort a list of students by grade and two students both have a B, a stable sort keeps them in the same relative order they were in before sorting.</p>
<div class="example-box">
<div class="label">Example -- Stability</div>
<p>Input: <code>[("Alice", B), ("Bob", A), ("Charlie", B)]</code></p>
<p><strong>Stable sort by grade:</strong> <code>[("Bob", A), ("Alice", B), ("Charlie", B)]</code> -- Alice still before Charlie</p>
<p><strong>Unstable sort by grade:</strong> <code>[("Bob", A), ("Charlie", B), ("Alice", B)]</code> -- order of B's might flip</p>
</div>
<div class="tip-box">
<div class="label">Tip</div>
<p>Stability matters when you sort by multiple keys. Sort by secondary key first, then by primary key with a stable sort, and the secondary ordering is preserved within groups.</p>
</div>
<div class="formula-box">
<strong>Which Sort to Use -- Decision Rules:</strong><br><br>
• n < 50: Insertion sort (low overhead, cache-friendly)<br>
• n ≥ 50, need stability: Merge sort -- O(n log n) guaranteed, stable, O(n) space<br>
• n ≥ 50, don't need stability: QuickSort -- O(n log n) average, O(n²) worst<br>
• Need guaranteed O(n log n) worst-case: Heap sort -- but not stable<br>
• Integer keys in range [0, k]: Counting sort -- O(n + k), not comparison-based<br><br>
<strong>Lower bound axiom:</strong> No comparison-based sort can do better than Ω(n log n) in the worst case. Proof: there are n! possible orderings; a binary decision tree needs at least log₂(n!) ≈ n log n comparisons to distinguish them all.
</div>
</section>
<!-- ============================== -->
<!-- 3. BUBBLE SORT -->
<!-- ============================== -->
<section id="bubble-sort">
<h2>3. Bubble Sort</h2>
<p><strong>Concept:</strong> Repeatedly walk through the array and swap adjacent elements if they are in the wrong order. After each full pass, the largest unsorted element "bubbles" up to its correct position at the end.</p>
<h3>Visual Walkthrough</h3>
<div class="example-box">
<div class="label">Step-by-Step: Sorting [5, 3, 8, 1, 2]</div>
<pre><code><span class="comment">Pass 1:</span>
[<span class="number">5</span>, <span class="number">3</span>, 8, 1, 2] → swap 5,3 → [<span class="number">3</span>, <span class="number">5</span>, 8, 1, 2]
[3, <span class="number">5</span>, <span class="number">8</span>, 1, 2] → no swap → [3, 5, 8, 1, 2]
[3, 5, <span class="number">8</span>, <span class="number">1</span>, 2] → swap 8,1 → [3, 5, <span class="number">1</span>, <span class="number">8</span>, 2]
[3, 5, 1, <span class="number">8</span>, <span class="number">2</span>] → swap 8,2 → [3, 5, 1, <span class="number">2</span>, <span class="number">8</span>]
<span class="comment">// 8 is now in its final position</span>
<span class="comment">Pass 2:</span>
[<span class="number">3</span>, <span class="number">5</span>, 1, 2, 8] → no swap → [3, 5, 1, 2, 8]
[3, <span class="number">5</span>, <span class="number">1</span>, 2, 8] → swap 5,1 → [3, <span class="number">1</span>, <span class="number">5</span>, 2, 8]
[3, 1, <span class="number">5</span>, <span class="number">2</span>, 8] → swap 5,2 → [3, 1, <span class="number">2</span>, <span class="number">5</span>, 8]
<span class="comment">// 5 is now in its final position</span>
<span class="comment">Pass 3:</span>
[<span class="number">3</span>, <span class="number">1</span>, 2, 5, 8] → swap 3,1 → [<span class="number">1</span>, <span class="number">3</span>, 2, 5, 8]
[1, <span class="number">3</span>, <span class="number">2</span>, 5, 8] → swap 3,2 → [1, <span class="number">2</span>, <span class="number">3</span>, 5, 8]
<span class="comment">// 3 is now in its final position</span>
<span class="comment">Pass 4:</span>
[<span class="number">1</span>, <span class="number">2</span>, 3, 5, 8] → no swaps → DONE!
<span class="comment">Result: [1, 2, 3, 5, 8]</span></code></pre>
</div>
<h3>Python Implementation</h3>
<pre><span class="lang-label">Python</span><code><span class="keyword">def</span> <span class="function">bubble_sort</span>(arr):
n = <span class="builtin">len</span>(arr)
<span class="keyword">for</span> i <span class="keyword">in</span> <span class="builtin">range</span>(n):
swapped = <span class="keyword">False</span>
<span class="keyword">for</span> j <span class="keyword">in</span> <span class="builtin">range</span>(n - <span class="number">1</span> - i):
<span class="keyword">if</span> arr[j] > arr[j + <span class="number">1</span>]:
arr[j], arr[j + <span class="number">1</span>] = arr[j + <span class="number">1</span>], arr[j]
swapped = <span class="keyword">True</span>
<span class="comment"># If no swaps happened, array is already sorted</span>
<span class="keyword">if not</span> swapped:
<span class="keyword">break</span>
<span class="keyword">return</span> arr
<span class="comment"># Example</span>
<span class="builtin">print</span>(<span class="function">bubble_sort</span>([<span class="number">5</span>, <span class="number">3</span>, <span class="number">8</span>, <span class="number">1</span>, <span class="number">2</span>])) <span class="comment"># [1, 2, 3, 5, 8]</span></code></pre>
<h3>JavaScript Implementation</h3>
<pre><span class="lang-label">JavaScript</span><code><span class="keyword">function</span> <span class="function">bubbleSort</span>(arr) {
<span class="keyword">const</span> n = arr.length;
<span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i < n; i++) {
<span class="keyword">let</span> swapped = <span class="keyword">false</span>;
<span class="keyword">for</span> (<span class="keyword">let</span> j = <span class="number">0</span>; j < n - <span class="number">1</span> - i; j++) {
<span class="keyword">if</span> (arr[j] > arr[j + <span class="number">1</span>]) {
[arr[j], arr[j + <span class="number">1</span>]] = [arr[j + <span class="number">1</span>], arr[j]];
swapped = <span class="keyword">true</span>;
}
}
<span class="comment">// If no swaps happened, array is already sorted</span>
<span class="keyword">if</span> (!swapped) <span class="keyword">break</span>;
}
<span class="keyword">return</span> arr;
}
<span class="comment">// Example</span>
console.<span class="function">log</span>(<span class="function">bubbleSort</span>([<span class="number">5</span>, <span class="number">3</span>, <span class="number">8</span>, <span class="number">1</span>, <span class="number">2</span>])); <span class="comment">// [1, 2, 3, 5, 8]</span></code></pre>
<div class="formula-box">
Time: O(n²) average/worst | O(n) best (already sorted) | Space: O(1) | Stable: Yes
</div>
<div class="warning-box">
<div class="label">Why It's Bad</div>
<p>Bubble sort is O(n²) in the average and worst case. It does far too many comparisons and swaps. Never use it in production code. The only scenario where it's acceptable is a nearly-sorted, very small array -- and even then, insertion sort is better.</p>
</div>
</section>
<!-- ============================== -->
<!-- 4. SELECTION SORT -->
<!-- ============================== -->
<section id="selection-sort">
<h2>4. Selection Sort</h2>
<p><strong>Concept:</strong> Find the minimum element in the unsorted portion, swap it with the first unsorted element, and move the boundary one step to the right. Repeat until the entire array is sorted.</p>
<h3>Visual Walkthrough</h3>
<div class="example-box">
<div class="label">Step-by-Step: Sorting [29, 10, 14, 37, 13]</div>
<pre><code><span class="comment">Pass 1: Find min in [29, 10, 14, 37, 13] → min is 10 at index 1</span>
Swap arr[0] and arr[1]: [<span class="number">10</span>, 29, 14, 37, 13]
Sorted: [<span class="number">10</span> | 29, 14, 37, 13]
<span class="comment">Pass 2: Find min in [29, 14, 37, 13] → min is 13 at index 4</span>
Swap arr[1] and arr[4]: [10, <span class="number">13</span>, 14, 37, 29]
Sorted: [10, <span class="number">13</span> | 14, 37, 29]
<span class="comment">Pass 3: Find min in [14, 37, 29] → min is 14 at index 2</span>
Already in place: [10, 13, <span class="number">14</span>, 37, 29]
Sorted: [10, 13, <span class="number">14</span> | 37, 29]
<span class="comment">Pass 4: Find min in [37, 29] → min is 29 at index 4</span>
Swap arr[3] and arr[4]: [10, 13, 14, <span class="number">29</span>, 37]
Sorted: [10, 13, 14, <span class="number">29</span> | 37]
<span class="comment">Result: [10, 13, 14, 29, 37]</span></code></pre>
</div>
<h3>Python Implementation</h3>
<pre><span class="lang-label">Python</span><code><span class="keyword">def</span> <span class="function">selection_sort</span>(arr):
n = <span class="builtin">len</span>(arr)
<span class="keyword">for</span> i <span class="keyword">in</span> <span class="builtin">range</span>(n):
<span class="comment"># Find the index of the minimum element in unsorted portion</span>
min_idx = i
<span class="keyword">for</span> j <span class="keyword">in</span> <span class="builtin">range</span>(i + <span class="number">1</span>, n):
<span class="keyword">if</span> arr[j] < arr[min_idx]:
min_idx = j
<span class="comment"># Swap the found minimum with the first unsorted element</span>
arr[i], arr[min_idx] = arr[min_idx], arr[i]
<span class="keyword">return</span> arr
<span class="comment"># Example</span>
<span class="builtin">print</span>(<span class="function">selection_sort</span>([<span class="number">29</span>, <span class="number">10</span>, <span class="number">14</span>, <span class="number">37</span>, <span class="number">13</span>])) <span class="comment"># [10, 13, 14, 29, 37]</span></code></pre>
<h3>JavaScript Implementation</h3>
<pre><span class="lang-label">JavaScript</span><code><span class="keyword">function</span> <span class="function">selectionSort</span>(arr) {
<span class="keyword">const</span> n = arr.length;
<span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i < n; i++) {
<span class="comment">// Find the index of the minimum element in unsorted portion</span>
<span class="keyword">let</span> minIdx = i;
<span class="keyword">for</span> (<span class="keyword">let</span> j = i + <span class="number">1</span>; j < n; j++) {
<span class="keyword">if</span> (arr[j] < arr[minIdx]) {
minIdx = j;
}
}
<span class="comment">// Swap the found minimum with the first unsorted element</span>
[arr[i], arr[minIdx]] = [arr[minIdx], arr[i]];
}
<span class="keyword">return</span> arr;
}
<span class="comment">// Example</span>
console.<span class="function">log</span>(<span class="function">selectionSort</span>([<span class="number">29</span>, <span class="number">10</span>, <span class="number">14</span>, <span class="number">37</span>, <span class="number">13</span>])); <span class="comment">// [10, 13, 14, 29, 37]</span></code></pre>
<div class="formula-box">
Time: O(n²) all cases | Space: O(1) | Stable: No
</div>
<div class="warning-box">
<div class="label">Not Stable</div>
<p>Selection sort is <strong>not stable</strong> because the swap can move equal elements past each other. It is also O(n²) in all cases -- even if the array is already sorted, it still scans for the minimum every pass. Don't use it in practice.</p>
</div>
</section>
<!-- ============================== -->
<!-- 5. INSERTION SORT -->
<!-- ============================== -->
<section id="insertion-sort">
<h2>5. Insertion Sort</h2>
<p><strong>Concept:</strong> Build the sorted array one element at a time. Take each element and insert it into its correct position in the already-sorted portion. Think of it like sorting a hand of playing cards -- you pick up each card and slide it into the right spot.</p>
<h3>Visual Walkthrough</h3>
<div class="example-box">
<div class="label">Step-by-Step: Sorting [5, 2, 4, 6, 1, 3]</div>
<pre><code><span class="comment">Start: sorted portion = [5], pick up 2</span>
2 < 5, shift 5 right, insert 2: [<span class="number">2</span>, <span class="number">5</span>, 4, 6, 1, 3]
<span class="comment">Pick up 4:</span>
4 < 5, shift 5 right. 4 > 2, stop. Insert 4: [2, <span class="number">4</span>, 5, 6, 1, 3]
<span class="comment">Pick up 6:</span>
6 > 5, already in place: [2, 4, 5, <span class="number">6</span>, 1, 3]
<span class="comment">Pick up 1:</span>
1 < 6, shift. 1 < 5, shift. 1 < 4, shift. 1 < 2, shift.
Insert 1 at front: [<span class="number">1</span>, 2, 4, 5, 6, 3]
<span class="comment">Pick up 3:</span>
3 < 6, shift. 3 < 5, shift. 3 < 4, shift. 3 > 2, stop.
Insert 3: [1, 2, <span class="number">3</span>, 4, 5, 6]
<span class="comment">Result: [1, 2, 3, 4, 5, 6]</span></code></pre>
</div>
<h3>Python Implementation</h3>
<pre><span class="lang-label">Python</span><code><span class="keyword">def</span> <span class="function">insertion_sort</span>(arr):
<span class="keyword">for</span> i <span class="keyword">in</span> <span class="builtin">range</span>(<span class="number">1</span>, <span class="builtin">len</span>(arr)):
key = arr[i] <span class="comment"># The element to insert</span>
j = i - <span class="number">1</span>
<span class="comment"># Shift elements of the sorted portion that are greater than key</span>
<span class="keyword">while</span> j >= <span class="number">0</span> <span class="keyword">and</span> arr[j] > key:
arr[j + <span class="number">1</span>] = arr[j]
j -= <span class="number">1</span>
arr[j + <span class="number">1</span>] = key <span class="comment"># Insert into correct position</span>
<span class="keyword">return</span> arr
<span class="comment"># Example</span>
<span class="builtin">print</span>(<span class="function">insertion_sort</span>([<span class="number">5</span>, <span class="number">2</span>, <span class="number">4</span>, <span class="number">6</span>, <span class="number">1</span>, <span class="number">3</span>])) <span class="comment"># [1, 2, 3, 4, 5, 6]</span></code></pre>
<h3>JavaScript Implementation</h3>
<pre><span class="lang-label">JavaScript</span><code><span class="keyword">function</span> <span class="function">insertionSort</span>(arr) {
<span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">1</span>; i < arr.length; i++) {
<span class="keyword">const</span> key = arr[i]; <span class="comment">// The element to insert</span>
<span class="keyword">let</span> j = i - <span class="number">1</span>;
<span class="comment">// Shift elements of the sorted portion that are greater than key</span>
<span class="keyword">while</span> (j >= <span class="number">0</span> && arr[j] > key) {
arr[j + <span class="number">1</span>] = arr[j];
j--;
}
arr[j + <span class="number">1</span>] = key; <span class="comment">// Insert into correct position</span>
}
<span class="keyword">return</span> arr;
}
<span class="comment">// Example</span>
console.<span class="function">log</span>(<span class="function">insertionSort</span>([<span class="number">5</span>, <span class="number">2</span>, <span class="number">4</span>, <span class="number">6</span>, <span class="number">1</span>, <span class="number">3</span>])); <span class="comment">// [1, 2, 3, 4, 5, 6]</span></code></pre>
<div class="formula-box">
Time: O(n²) average/worst | O(n) best (already sorted) | Space: O(1) | Stable: Yes
</div>
<div class="tip-box">
<div class="label">Actually Useful</div>
<p>Unlike bubble and selection sort, insertion sort is actually used in practice. Python's built-in <code>sorted()</code> uses <strong>Timsort</strong>, which is a hybrid of merge sort and insertion sort. Timsort uses insertion sort for small subarrays (typically < 64 elements) because insertion sort has low overhead and is very fast on small or nearly-sorted data.</p>
</div>
</section>
<!-- ============================== -->
<!-- 6. MERGE SORT -->
<!-- ============================== -->
<section id="merge-sort">
<h2>6. Merge Sort (Important)</h2>
<p><strong>Concept:</strong> Divide the array in half, recursively sort each half, then merge the two sorted halves back together. This is a classic <strong>divide and conquer</strong> algorithm.</p>
<h3>The Divide and Conquer Approach</h3>
<ol>
<li><strong>Divide:</strong> Split the array into two halves.</li>
<li><strong>Conquer:</strong> Recursively sort each half (base case: array of size 0 or 1 is already sorted).</li>
<li><strong>Combine:</strong> Merge the two sorted halves into one sorted array.</li>
</ol>
<h3>Visual Walkthrough</h3>
<div class="example-box">
<div class="label">Splitting and Merging [38, 27, 43, 3, 9, 82, 10]</div>
<pre><code><span class="comment">SPLIT phase (divide into halves):</span>
[38, 27, 43, 3, 9, 82, 10]
/ \
[38, 27, 43, 3] [9, 82, 10]
/ \ / \
[38, 27] [43, 3] [9, 82] [10]
/ \ / \ / \
[38] [27] [43] [3] [9] [82]
<span class="comment">MERGE phase (combine sorted halves):</span>
[38] [27] [43] [3] [9] [82] [10]
\ / \ / \ /
[27, 38] [3, 43] [9, 82] [10]
\ / \ /
[3, 27, 38, 43] [9, 10, 82]
\ /
[3, 9, 10, 27, 38, 43, 82]</code></pre>
</div>
<h3>Python Implementation</h3>
<pre><span class="lang-label">Python</span><code><span class="keyword">def</span> <span class="function">merge_sort</span>(arr):
<span class="comment"># Base case: array of length 0 or 1 is already sorted</span>
<span class="keyword">if</span> <span class="builtin">len</span>(arr) <= <span class="number">1</span>:
<span class="keyword">return</span> arr
<span class="comment"># DIVIDE: split array into two halves</span>
mid = <span class="builtin">len</span>(arr) // <span class="number">2</span>
left = <span class="function">merge_sort</span>(arr[:mid]) <span class="comment"># Recursively sort left half</span>
right = <span class="function">merge_sort</span>(arr[mid:]) <span class="comment"># Recursively sort right half</span>
<span class="comment"># MERGE: combine two sorted halves</span>
<span class="keyword">return</span> <span class="function">merge</span>(left, right)
<span class="keyword">def</span> <span class="function">merge</span>(left, right):
result = []
i = j = <span class="number">0</span>
<span class="comment"># Compare elements from both halves, pick the smaller one</span>
<span class="keyword">while</span> i < <span class="builtin">len</span>(left) <span class="keyword">and</span> j < <span class="builtin">len</span>(right):
<span class="keyword">if</span> left[i] <= right[j]: <span class="comment"># <= makes it stable</span>
result.<span class="function">append</span>(left[i])
i += <span class="number">1</span>
<span class="keyword">else</span>:
result.<span class="function">append</span>(right[j])
j += <span class="number">1</span>
<span class="comment"># Append remaining elements (one half may have leftovers)</span>
result.<span class="function">extend</span>(left[i:])
result.<span class="function">extend</span>(right[j:])
<span class="keyword">return</span> result
<span class="comment"># Example</span>
<span class="builtin">print</span>(<span class="function">merge_sort</span>([<span class="number">38</span>, <span class="number">27</span>, <span class="number">43</span>, <span class="number">3</span>, <span class="number">9</span>, <span class="number">82</span>, <span class="number">10</span>]))
<span class="comment"># [3, 9, 10, 27, 38, 43, 82]</span></code></pre>
<h3>JavaScript Implementation</h3>
<pre><span class="lang-label">JavaScript</span><code><span class="keyword">function</span> <span class="function">mergeSort</span>(arr) {
<span class="comment">// Base case: array of length 0 or 1 is already sorted</span>
<span class="keyword">if</span> (arr.length <= <span class="number">1</span>) <span class="keyword">return</span> arr;
<span class="comment">// DIVIDE: split array into two halves</span>
<span class="keyword">const</span> mid = Math.<span class="function">floor</span>(arr.length / <span class="number">2</span>);
<span class="keyword">const</span> left = <span class="function">mergeSort</span>(arr.<span class="function">slice</span>(<span class="number">0</span>, mid)); <span class="comment">// Recursively sort left</span>
<span class="keyword">const</span> right = <span class="function">mergeSort</span>(arr.<span class="function">slice</span>(mid)); <span class="comment">// Recursively sort right</span>
<span class="comment">// MERGE: combine two sorted halves</span>
<span class="keyword">return</span> <span class="function">merge</span>(left, right);
}
<span class="keyword">function</span> <span class="function">merge</span>(left, right) {
<span class="keyword">const</span> result = [];
<span class="keyword">let</span> i = <span class="number">0</span>, j = <span class="number">0</span>;
<span class="comment">// Compare elements from both halves, pick the smaller one</span>
<span class="keyword">while</span> (i < left.length && j < right.length) {
<span class="keyword">if</span> (left[i] <= right[j]) { <span class="comment">// <= makes it stable</span>
result.<span class="function">push</span>(left[i]);
i++;
} <span class="keyword">else</span> {
result.<span class="function">push</span>(right[j]);
j++;
}
}
<span class="comment">// Append remaining elements</span>
<span class="keyword">return</span> result.<span class="function">concat</span>(left.<span class="function">slice</span>(i)).<span class="function">concat</span>(right.<span class="function">slice</span>(j));
}
<span class="comment">// Example</span>
console.<span class="function">log</span>(<span class="function">mergeSort</span>([<span class="number">38</span>, <span class="number">27</span>, <span class="number">43</span>, <span class="number">3</span>, <span class="number">9</span>, <span class="number">82</span>, <span class="number">10</span>]));
<span class="comment">// [3, 9, 10, 27, 38, 43, 82]</span></code></pre>
<div class="formula-box">
Time: O(n log n) all cases | Space: O(n) | Stable: Yes
</div>
<ul>
<li><strong>Always O(n log n)</strong> -- very predictable performance, no worst-case degradation.</li>
<li><strong>Downside:</strong> O(n) extra space for the temporary arrays during merging.</li>
<li><strong>Used in:</strong> Python's <code>sorted()</code> (Timsort is a hybrid of merge sort + insertion sort), Java's <code>Arrays.sort()</code> for objects, external sorting (sorting data that doesn't fit in memory).</li>
</ul>
<div class="tip-box">
<div class="label">Interview Tip</div>
<p>Merge sort is a top interview topic. You should be able to write it from memory. The key insight is that merging two sorted arrays is O(n) -- you just compare the fronts of both arrays and pick the smaller one.</p>
</div>
</section>
<!-- ============================== -->
<!-- 7. QUICK SORT -->
<!-- ============================== -->
<section id="quick-sort">
<h2>7. Quick Sort (Important)</h2>
<p><strong>Concept:</strong> Pick a "pivot" element, then partition the array so that all elements less than the pivot come before it and all elements greater come after it. Recursively sort the two partitions.</p>
<h3>The Partition Step (Detailed)</h3>
<p>The partition is the heart of quick sort. Here is how Lomuto's partition scheme works:</p>
<ol>
<li>Choose the last element as the pivot.</li>
<li>Maintain a pointer <code>i</code> that tracks where the next "smaller than pivot" element should go.</li>
<li>Walk through the array with pointer <code>j</code>. If <code>arr[j] < pivot</code>, swap <code>arr[i]</code> and <code>arr[j]</code>, then increment <code>i</code>.</li>
<li>After scanning, swap the pivot into position <code>i</code>. Now everything left of <code>i</code> is smaller, everything right is larger.</li>
</ol>
<h3>Visual Walkthrough</h3>
<div class="example-box">
<div class="label">Partitioning [10, 80, 30, 90, 40, 50, 70] with pivot = 70</div>
<pre><code><span class="comment">pivot = 70 (last element), i = 0</span>
j=0: arr[0]=10 < 70 → swap arr[0],arr[0], i=1 [<span class="number">10</span>, 80, 30, 90, 40, 50, 70]
j=1: arr[1]=80 > 70 → skip [10, 80, 30, 90, 40, 50, 70]
j=2: arr[2]=30 < 70 → swap arr[1],arr[2], i=2 [10, <span class="number">30</span>, <span class="number">80</span>, 90, 40, 50, 70]
j=3: arr[3]=90 > 70 → skip [10, 30, 80, 90, 40, 50, 70]
j=4: arr[4]=40 < 70 → swap arr[2],arr[4], i=3 [10, 30, <span class="number">40</span>, 90, <span class="number">80</span>, 50, 70]
j=5: arr[5]=50 < 70 → swap arr[3],arr[5], i=4 [10, 30, 40, <span class="number">50</span>, 80, <span class="number">90</span>, 70]
<span class="comment">Swap pivot (70) into position i=4:</span>
[10, 30, 40, 50, <span class="number">70</span>, 90, 80]
<span class="comment">Now: [10, 30, 40, 50] < 70 < [90, 80]</span>
<span class="comment">Recursively sort left and right partitions.</span></code></pre>
</div>
<h3>Python Implementation</h3>
<pre><span class="lang-label">Python</span><code><span class="keyword">def</span> <span class="function">quick_sort</span>(arr):
<span class="comment"># Simple version using list comprehensions (Pythonic but uses extra space)</span>
<span class="keyword">if</span> <span class="builtin">len</span>(arr) <= <span class="number">1</span>:
<span class="keyword">return</span> arr
pivot = arr[<span class="builtin">len</span>(arr) // <span class="number">2</span>] <span class="comment"># Choose middle element as pivot</span>
left = [x <span class="keyword">for</span> x <span class="keyword">in</span> arr <span class="keyword">if</span> x < pivot]
middle = [x <span class="keyword">for</span> x <span class="keyword">in</span> arr <span class="keyword">if</span> x == pivot]
right = [x <span class="keyword">for</span> x <span class="keyword">in</span> arr <span class="keyword">if</span> x > pivot]
<span class="keyword">return</span> <span class="function">quick_sort</span>(left) + middle + <span class="function">quick_sort</span>(right)
<span class="comment"># In-place version (more efficient, what interviewers want to see)</span>
<span class="keyword">def</span> <span class="function">quick_sort_inplace</span>(arr, low=<span class="number">0</span>, high=<span class="keyword">None</span>):
<span class="keyword">if</span> high <span class="keyword">is</span> <span class="keyword">None</span>:
high = <span class="builtin">len</span>(arr) - <span class="number">1</span>
<span class="keyword">if</span> low < high:
<span class="comment"># Partition and get pivot index</span>
pivot_idx = <span class="function">partition</span>(arr, low, high)
<span class="comment"># Recursively sort left and right of pivot</span>
<span class="function">quick_sort_inplace</span>(arr, low, pivot_idx - <span class="number">1</span>)
<span class="function">quick_sort_inplace</span>(arr, pivot_idx + <span class="number">1</span>, high)
<span class="keyword">return</span> arr
<span class="keyword">def</span> <span class="function">partition</span>(arr, low, high):
pivot = arr[high] <span class="comment"># Choose last element as pivot</span>
i = low <span class="comment"># Pointer for "smaller than pivot" boundary</span>
<span class="keyword">for</span> j <span class="keyword">in</span> <span class="builtin">range</span>(low, high):
<span class="keyword">if</span> arr[j] < pivot:
arr[i], arr[j] = arr[j], arr[i]
i += <span class="number">1</span>
<span class="comment"># Place pivot in its correct position</span>
arr[i], arr[high] = arr[high], arr[i]
<span class="keyword">return</span> i
<span class="comment"># Example</span>
<span class="builtin">print</span>(<span class="function">quick_sort</span>([<span class="number">10</span>, <span class="number">80</span>, <span class="number">30</span>, <span class="number">90</span>, <span class="number">40</span>, <span class="number">50</span>, <span class="number">70</span>]))
<span class="comment"># [10, 30, 40, 50, 70, 80, 90]</span>
<span class="builtin">print</span>(<span class="function">quick_sort_inplace</span>([<span class="number">10</span>, <span class="number">80</span>, <span class="number">30</span>, <span class="number">90</span>, <span class="number">40</span>, <span class="number">50</span>, <span class="number">70</span>]))
<span class="comment"># [10, 30, 40, 50, 70, 80, 90]</span></code></pre>
<h3>JavaScript Implementation</h3>
<pre><span class="lang-label">JavaScript</span><code><span class="comment">// Simple version (uses extra space)</span>
<span class="keyword">function</span> <span class="function">quickSort</span>(arr) {
<span class="keyword">if</span> (arr.length <= <span class="number">1</span>) <span class="keyword">return</span> arr;
<span class="keyword">const</span> pivot = arr[Math.<span class="function">floor</span>(arr.length / <span class="number">2</span>)];
<span class="keyword">const</span> left = arr.<span class="function">filter</span>(x => x < pivot);
<span class="keyword">const</span> middle = arr.<span class="function">filter</span>(x => x === pivot);
<span class="keyword">const</span> right = arr.<span class="function">filter</span>(x => x > pivot);
<span class="keyword">return</span> [...<span class="function">quickSort</span>(left), ...middle, ...<span class="function">quickSort</span>(right)];
}
<span class="comment">// In-place version (efficient, interview-ready)</span>
<span class="keyword">function</span> <span class="function">quickSortInPlace</span>(arr, low = <span class="number">0</span>, high = arr.length - <span class="number">1</span>) {
<span class="keyword">if</span> (low < high) {
<span class="keyword">const</span> pivotIdx = <span class="function">partition</span>(arr, low, high);
<span class="function">quickSortInPlace</span>(arr, low, pivotIdx - <span class="number">1</span>);
<span class="function">quickSortInPlace</span>(arr, pivotIdx + <span class="number">1</span>, high);
}
<span class="keyword">return</span> arr;
}
<span class="keyword">function</span> <span class="function">partition</span>(arr, low, high) {
<span class="keyword">const</span> pivot = arr[high]; <span class="comment">// Choose last element as pivot</span>
<span class="keyword">let</span> i = low; <span class="comment">// Boundary pointer</span>
<span class="keyword">for</span> (<span class="keyword">let</span> j = low; j < high; j++) {
<span class="keyword">if</span> (arr[j] < pivot) {
[arr[i], arr[j]] = [arr[j], arr[i]];
i++;
}
}
<span class="comment">// Place pivot in correct position</span>
[arr[i], arr[high]] = [arr[high], arr[i]];
<span class="keyword">return</span> i;
}
<span class="comment">// Example</span>
console.<span class="function">log</span>(<span class="function">quickSort</span>([<span class="number">10</span>, <span class="number">80</span>, <span class="number">30</span>, <span class="number">90</span>, <span class="number">40</span>, <span class="number">50</span>, <span class="number">70</span>]));
<span class="comment">// [10, 30, 40, 50, 70, 80, 90]</span></code></pre>
<div class="formula-box">
Time: O(n log n) avg | O(n²) worst (bad pivot) | Space: O(log n) stack | Stable: No
</div>
<h3>Pivot Selection Strategies</h3>
<ul>
<li><strong>Last element:</strong> Simple but vulnerable to sorted/reverse-sorted input (degrades to O(n²)).</li>
<li><strong>Random element:</strong> Swap a random element to the end before partitioning. Makes worst case extremely unlikely.</li>
<li><strong>Median-of-three:</strong> Take the median of the first, middle, and last elements. Good compromise between simplicity and performance.</li>
</ul>
<div class="tip-box">
<div class="label">In Practice</div>
<p>Quick sort is generally the fastest comparison-based sorting algorithm in practice due to excellent cache locality and low constant factors. Most standard library sorts (C's <code>qsort</code>, C++'s <code>std::sort</code>) use some variant of quick sort (often introsort, which falls back to heap sort if recursion gets too deep).</p>
</div>
<div class="warning-box">
<div class="label">QuickSort Worst Case Trigger</div>
<p><strong>O(n²) occurs when:</strong> The pivot is always the min or max element (e.g., already-sorted input with first-element pivot).</p>
<p><strong>Fix:</strong> Use random pivot selection or median-of-three. This makes worst case astronomically unlikely -- O(n log n) expected.</p>
</div>
</section>
<!-- ============================== -->
<!-- 8. HEAP SORT -->
<!-- ============================== -->
<section id="heap-sort">
<h2>8. Heap Sort (Brief)</h2>
<p><strong>Concept:</strong> Build a max heap from the array, then repeatedly extract the maximum element and place it at the end.</p>
<h3>How It Works</h3>
<ol>
<li><strong>Build a max heap</strong> from the input array. A max heap is a complete binary tree where every parent is greater than or equal to its children.</li>
<li><strong>Extract the max</strong> (root of the heap) and swap it with the last element of the heap.</li>
<li><strong>Reduce heap size</strong> by one and "heapify" the root to restore the heap property.</li>
<li><strong>Repeat</strong> until the heap is empty. The array is now sorted.</li>
</ol>
<div class="formula-box">
Time: O(n log n) all cases | Space: O(1) | Stable: No
</div>
<ul>
<li><strong>Guaranteed O(n log n)</strong> with O(1) extra space -- the only algorithm that offers both.</li>
<li><strong>Downsides:</strong> Poor cache locality (jumps around the array), higher constant factors than quick sort. Rarely the fastest in practice.</li>
<li><strong>Best for:</strong> When you need guaranteed O(n log n) with no extra memory.</li>
</ul>
<div class="tip-box">
<div class="label">Learn More</div>
<p>Heaps are covered in detail on the <a href="advanced.html" class="resource-link">Advanced Data Structures</a> page, including heap implementation, heapify, and priority queues.</p>
</div>
</section>
<!-- ============================== -->
<!-- 9. COUNTING & RADIX SORT -->
<!-- ============================== -->
<section id="counting-radix">
<h2>9. Counting Sort & Radix Sort (Brief)</h2>
<p>These are <strong>non-comparison sorts</strong>. They don't compare elements to each other -- instead, they exploit the structure of the data to sort faster than O(n log n).</p>
<h3>Counting Sort</h3>
<p><strong>When to use:</strong> You know the range of values is small (for example, sorting grades 0-100, or characters a-z).</p>
<ol>
<li>Count occurrences of each value.</li>
<li>Build a cumulative count array.</li>
<li>Place each element in its correct position using the counts.</li>
</ol>
<pre><span class="lang-label">Python</span><code><span class="keyword">def</span> <span class="function">counting_sort</span>(arr, max_val):
<span class="comment"># Count occurrences of each value</span>
count = [<span class="number">0</span>] * (max_val + <span class="number">1</span>)
<span class="keyword">for</span> num <span class="keyword">in</span> arr:
count[num] += <span class="number">1</span>
<span class="comment"># Build sorted array from counts</span>
result = []
<span class="keyword">for</span> val <span class="keyword">in</span> <span class="builtin">range</span>(max_val + <span class="number">1</span>):
result.<span class="function">extend</span>([val] * count[val])
<span class="keyword">return</span> result
<span class="comment"># Example: sorting grades (range 0-5)</span>
<span class="builtin">print</span>(<span class="function">counting_sort</span>([<span class="number">4</span>, <span class="number">2</span>, <span class="number">2</span>, <span class="number">8</span>, <span class="number">3</span>, <span class="number">3</span>, <span class="number">1</span>], <span class="number">8</span>))
<span class="comment"># [1, 2, 2, 3, 3, 4, 8]</span></code></pre>
<pre><span class="lang-label">JavaScript</span><code><span class="keyword">function</span> <span class="function">countingSort</span>(arr, maxVal) {
<span class="keyword">const</span> count = <span class="keyword">new</span> <span class="builtin">Array</span>(maxVal + <span class="number">1</span>).<span class="function">fill</span>(<span class="number">0</span>);
<span class="keyword">for</span> (<span class="keyword">const</span> num <span class="keyword">of</span> arr) count[num]++;
<span class="keyword">const</span> result = [];
<span class="keyword">for</span> (<span class="keyword">let</span> val = <span class="number">0</span>; val <= maxVal; val++) {
<span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i < count[val]; i++) {
result.<span class="function">push</span>(val);
}
}
<span class="keyword">return</span> result;
}
console.<span class="function">log</span>(<span class="function">countingSort</span>([<span class="number">4</span>, <span class="number">2</span>, <span class="number">2</span>, <span class="number">8</span>, <span class="number">3</span>, <span class="number">3</span>, <span class="number">1</span>], <span class="number">8</span>));
<span class="comment">// [1, 2, 2, 3, 3, 4, 8]</span></code></pre>
<div class="formula-box">
Counting Sort: Time O(n + k) | Space O(k) | k = range of values
</div>
<h3>Radix Sort</h3>
<p><strong>Concept:</strong> Sort numbers digit by digit, starting from the least significant digit to the most significant. Uses counting sort (or any stable sort) as a subroutine for each digit.</p>
<ul>
<li><strong>Time:</strong> O(nk) where k = number of digits.</li>
<li><strong>Space:</strong> O(n + k).</li>
<li><strong>When to use:</strong> Large arrays of integers with a known, bounded number of digits.</li>
</ul>
<div class="warning-box">
<div class="label">Limitation</div>
<p>Non-comparison sorts only work with specific data types (integers, strings of fixed length). They cannot sort arbitrary objects. For general-purpose sorting, you need comparison-based algorithms.</p>
</div>
</section>
<!-- ============================== -->
<!-- 10. BINARY SEARCH -->
<!-- ============================== -->
<section id="binary-search">
<h2>10. Binary Search (Very Important)</h2>
<p><strong>Prerequisite:</strong> The array must be sorted.</p>
<p><strong>Concept:</strong> Compare the target with the middle element. If the target is smaller, search the left half. If larger, search the right half. Eliminate half the remaining elements with each comparison.</p>
<div class="formula-box">
Time: O(log n) | Space: O(1) iterative, O(log n) recursive
</div>
<h3>Why O(log n)?</h3>
<p>Each step cuts the search space in half. Starting with n elements: n → n/2 → n/4 → ... → 1. The number of steps to go from n to 1 by halving is log&sub2;(n). For an array of 1,000,000 elements, binary search takes at most ~20 comparisons.</p>
<h3>Iterative Binary Search</h3>
<pre><span class="lang-label">Python</span><code><span class="keyword">def</span> <span class="function">binary_search</span>(arr, target):
left, right = <span class="number">0</span>, <span class="builtin">len</span>(arr) - <span class="number">1</span>
<span class="keyword">while</span> left <= right:
mid = (left + right) // <span class="number">2</span> <span class="comment"># or left + (right - left) // 2 to avoid overflow</span>
<span class="keyword">if</span> arr[mid] == target:
<span class="keyword">return</span> mid <span class="comment"># Found it!</span>
<span class="keyword">elif</span> arr[mid] < target:
left = mid + <span class="number">1</span> <span class="comment"># Target is in right half</span>
<span class="keyword">else</span>:
right = mid - <span class="number">1</span> <span class="comment"># Target is in left half</span>
<span class="keyword">return</span> -<span class="number">1</span> <span class="comment"># Not found</span>
<span class="comment"># Example</span>
arr = [<span class="number">1</span>, <span class="number">3</span>, <span class="number">5</span>, <span class="number">7</span>, <span class="number">9</span>, <span class="number">11</span>, <span class="number">13</span>]
<span class="builtin">print</span>(<span class="function">binary_search</span>(arr, <span class="number">7</span>)) <span class="comment"># 3 (index)</span>
<span class="builtin">print</span>(<span class="function">binary_search</span>(arr, <span class="number">4</span>)) <span class="comment"># -1 (not found)</span></code></pre>
<pre><span class="lang-label">JavaScript</span><code><span class="keyword">function</span> <span class="function">binarySearch</span>(arr, target) {
<span class="keyword">let</span> left = <span class="number">0</span>, right = arr.length - <span class="number">1</span>;
<span class="keyword">while</span> (left <= right) {
<span class="keyword">const</span> mid = Math.<span class="function">floor</span>((left + right) / <span class="number">2</span>);
<span class="keyword">if</span> (arr[mid] === target) <span class="keyword">return</span> mid;
<span class="keyword">else if</span> (arr[mid] < target) left = mid + <span class="number">1</span>;
<span class="keyword">else</span> right = mid - <span class="number">1</span>;
}
<span class="keyword">return</span> -<span class="number">1</span>;
}
<span class="comment">// Example</span>
<span class="keyword">const</span> arr = [<span class="number">1</span>, <span class="number">3</span>, <span class="number">5</span>, <span class="number">7</span>, <span class="number">9</span>, <span class="number">11</span>, <span class="number">13</span>];
console.<span class="function">log</span>(<span class="function">binarySearch</span>(arr, <span class="number">7</span>)); <span class="comment">// 3</span>
console.<span class="function">log</span>(<span class="function">binarySearch</span>(arr, <span class="number">4</span>)); <span class="comment">// -1</span></code></pre>
<h3>Recursive Binary Search</h3>
<pre><span class="lang-label">Python</span><code><span class="keyword">def</span> <span class="function">binary_search_recursive</span>(arr, target, left=<span class="number">0</span>, right=<span class="keyword">None</span>):
<span class="keyword">if</span> right <span class="keyword">is</span> <span class="keyword">None</span>:
right = <span class="builtin">len</span>(arr) - <span class="number">1</span>
<span class="keyword">if</span> left > right:
<span class="keyword">return</span> -<span class="number">1</span> <span class="comment"># Base case: not found</span>
mid = (left + right) // <span class="number">2</span>
<span class="keyword">if</span> arr[mid] == target:
<span class="keyword">return</span> mid
<span class="keyword">elif</span> arr[mid] < target:
<span class="keyword">return</span> <span class="function">binary_search_recursive</span>(arr, target, mid + <span class="number">1</span>, right)
<span class="keyword">else</span>:
<span class="keyword">return</span> <span class="function">binary_search_recursive</span>(arr, target, left, mid - <span class="number">1</span>)</code></pre>
<pre><span class="lang-label">JavaScript</span><code><span class="keyword">function</span> <span class="function">binarySearchRecursive</span>(arr, target, left = <span class="number">0</span>, right = arr.length - <span class="number">1</span>) {
<span class="keyword">if</span> (left > right) <span class="keyword">return</span> -<span class="number">1</span>;
<span class="keyword">const</span> mid = Math.<span class="function">floor</span>((left + right) / <span class="number">2</span>);
<span class="keyword">if</span> (arr[mid] === target) <span class="keyword">return</span> mid;
<span class="keyword">if</span> (arr[mid] < target) <span class="keyword">return</span> <span class="function">binarySearchRecursive</span>(arr, target, mid + <span class="number">1</span>, right);
<span class="keyword">return</span> <span class="function">binarySearchRecursive</span>(arr, target, left, mid - <span class="number">1</span>);
}</code></pre>
<h3>Variation: Find Leftmost (bisect_left)</h3>
<p>Find the first position where target could be inserted to keep the array sorted. If target exists, returns its leftmost index.</p>
<pre><span class="lang-label">Python</span><code><span class="keyword">def</span> <span class="function">bisect_left</span>(arr, target):
left, right = <span class="number">0</span>, <span class="builtin">len</span>(arr)
<span class="keyword">while</span> left < right:
mid = (left + right) // <span class="number">2</span>
<span class="keyword">if</span> arr[mid] < target:
left = mid + <span class="number">1</span>
<span class="keyword">else</span>:
right = mid <span class="comment"># Don't skip mid -- it might be the answer</span>
<span class="keyword">return</span> left
<span class="comment"># Example: [1, 2, 2, 2, 3, 4]</span>
<span class="comment"># bisect_left(arr, 2) = 1 (leftmost index of 2)</span></code></pre>
<pre><span class="lang-label">JavaScript</span><code><span class="keyword">function</span> <span class="function">bisectLeft</span>(arr, target) {
<span class="keyword">let</span> left = <span class="number">0</span>, right = arr.length;
<span class="keyword">while</span> (left < right) {
<span class="keyword">const</span> mid = Math.<span class="function">floor</span>((left + right) / <span class="number">2</span>);
<span class="keyword">if</span> (arr[mid] < target) left = mid + <span class="number">1</span>;
<span class="keyword">else</span> right = mid;
}
<span class="keyword">return</span> left;
}</code></pre>
<h3>Variation: Find Rightmost (bisect_right)</h3>
<p>Find the first position after all occurrences of target.</p>
<pre><span class="lang-label">Python</span><code><span class="keyword">def</span> <span class="function">bisect_right</span>(arr, target):
left, right = <span class="number">0</span>, <span class="builtin">len</span>(arr)
<span class="keyword">while</span> left < right:
mid = (left + right) // <span class="number">2</span>
<span class="keyword">if</span> arr[mid] <= target:
left = mid + <span class="number">1</span> <span class="comment"># Skip past equal elements</span>
<span class="keyword">else</span>:
right = mid
<span class="keyword">return</span> left
<span class="comment"># Example: [1, 2, 2, 2, 3, 4]</span>
<span class="comment"># bisect_right(arr, 2) = 4 (first index after all 2s)</span></code></pre>