-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
788 lines (736 loc) · 32.9 KB
/
index.html
File metadata and controls
788 lines (736 loc) · 32.9 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
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Học Giải Thuật - CTDL></title>
<style>
*{box-sizing:border-box;margin:0;padding:0}
body{font-family:system-ui,sans-serif;background:#f5f5f0;color:#1a1a1a;min-height:100vh}
.header{background:#1a1a2e;color:#fff;padding:16px 24px;display:flex;align-items:center;gap:12px}
.header h1{font-size:18px;font-weight:500}
.header span{font-size:13px;color:#aaa;margin-left:auto}
.layout{display:flex;height:calc(100vh - 56px)}
.sidebar{width:220px;background:#fff;border-right:1px solid #e0e0e0;overflow-y:auto;flex-shrink:0}
.sidebar-group{padding:8px 0}
.sidebar-group-title{font-size:11px;font-weight:600;color:#888;letter-spacing:.08em;padding:8px 16px 4px;text-transform:uppercase}
.sidebar-item{display:block;padding:8px 16px;font-size:13px;color:#444;cursor:pointer;border:none;background:none;width:100%;text-align:left;border-left:3px solid transparent;transition:all .15s}
.sidebar-item:hover{background:#f5f5f0;color:#1a1a2e}
.sidebar-item.active{background:#eef;color:#1a1a2e;border-left-color:#5b4fcf;font-weight:500}
.main{flex:1;overflow:auto;padding:24px;display:flex;flex-direction:column;gap:20px}
.card{background:#fff;border:1px solid #e0e0e0;border-radius:10px;overflow:hidden}
.card-header{padding:14px 20px;border-bottom:1px solid #e0e0e0;display:flex;align-items:center;gap:10px}
.card-header h2{font-size:15px;font-weight:500}
.badge{font-size:11px;padding:3px 8px;border-radius:20px;font-weight:500}
.badge-sort{background:#e8f4fd;color:#1565c0}
.badge-search{background:#e8f7ed;color:#2e7d32}
.badge-tree{background:#fdf3e8;color:#e65100}
.card-body{padding:20px}
/* Input section */
.input-row{display:flex;gap:8px;align-items:center;flex-wrap:wrap;margin-bottom:12px}
.input-row label{font-size:13px;color:#555;min-width:80px}
input[type=text],input[type=number]{border:1px solid #ddd;border-radius:6px;padding:7px 12px;font-size:13px;color:#1a1a2e;outline:none;transition:border-color .15s}
input[type=text]:focus,input[type=number]:focus{border-color:#5b4fcf}
.input-array{flex:1;min-width:180px}
.input-x{width:90px}
.btn{padding:8px 16px;border-radius:6px;font-size:13px;cursor:pointer;border:1px solid;font-weight:500;transition:all .15s}
.btn-primary{background:#1a1a2e;color:#fff;border-color:#1a1a2e}
.btn-primary:hover{background:#2d2d4e}
.btn-reset{background:#fff;color:#555;border-color:#ddd}
.btn-reset:hover{background:#f5f5f0}
.btn-step{background:#5b4fcf;color:#fff;border-color:#5b4fcf}
.btn-step:hover{background:#4a3fbf}
.btn-auto{background:#0d7a3e;color:#fff;border-color:#0d7a3e}
.btn-auto:hover{background:#0a5f30}
/* Array visualization */
.array-viz{display:flex;gap:4px;align-items:flex-end;min-height:80px;margin:12px 0;flex-wrap:wrap}
.arr-cell{display:flex;flex-direction:column;align-items:center;gap:3px}
.arr-bar{width:36px;background:#c7c3f7;border-radius:4px 4px 0 0;transition:all .3s;min-height:10px;position:relative}
.arr-bar.active{background:#5b4fcf}
.arr-bar.comparing{background:#f59e0b}
.arr-bar.sorted{background:#10b981}
.arr-bar.found{background:#ef4444;animation:pulse .5s infinite alternate}
.arr-bar.pivot{background:#ec4899}
.arr-label{font-size:11px;color:#555;font-weight:500}
.arr-idx{font-size:10px;color:#aaa}
@keyframes pulse{from{opacity:1}to{opacity:.5}}
/* Steps log */
.steps-log{background:#f8f8f5;border:1px solid #e0e0e0;border-radius:6px;padding:10px 14px;font-size:12px;color:#444;max-height:160px;overflow-y:auto;font-family:monospace;line-height:1.8}
.step-entry{padding:1px 0;border-bottom:1px solid #f0f0ea}
.step-entry:last-child{border:none;color:#1a1a2e;font-weight:600}
/* Pseudocode */
.pseudocode{background:#1e1e2e;color:#cdd6f4;border-radius:8px;padding:14px 18px;font-family:monospace;font-size:12px;line-height:1.8;overflow-x:auto}
.ps-kw{color:#89b4fa}
.ps-fn{color:#a6e3a1}
.ps-cmt{color:#6c7086}
.ps-hl{background:#2d2d4e;border-radius:2px;display:block}
/* Tree viz */
.tree-canvas{width:100%;background:#f8f8f5;border-radius:8px;border:1px solid #e0e0e0}
/* Result box */
.result-box{padding:10px 14px;border-radius:6px;font-size:13px;font-weight:500;margin-top:10px}
.result-ok{background:#e8f7ed;color:#2e7d32;border:1px solid #a5d6a7}
.result-err{background:#fdecea;color:#c62828;border:1px solid #ef9a9a}
.result-info{background:#e8f4fd;color:#1565c0;border:1px solid #90caf9}
.tabs{display:flex;gap:0;border-bottom:1px solid #e0e0e0}
.tab{padding:8px 16px;font-size:13px;cursor:pointer;border:none;background:none;color:#666;border-bottom:2px solid transparent;margin-bottom:-1px}
.tab.active{color:#5b4fcf;border-bottom-color:#5b4fcf;font-weight:500}
.tab-content{display:none;padding:16px 0 0}
.tab-content.active{display:block}
.stat-row{display:flex;gap:12px;margin-top:10px}
.stat{background:#f5f5f0;border-radius:6px;padding:8px 14px;font-size:12px;flex:1;text-align:center}
.stat-val{font-size:20px;font-weight:500;color:#1a1a2e}
.stat-lbl{color:#888;font-size:11px}
.speed-row{display:flex;align-items:center;gap:8px;font-size:12px;color:#666}
.speed-row input[type=range]{width:100px}
</style>
</head>
<body>
<div class="header">
<div style="width:28px;height:28px;background:#5b4fcf;border-radius:6px;display:flex;align-items:center;justify-content:center;font-size:14px;color:#fff;font-weight:700">G</div>
<h1>Học Giải Thuật — CTDL></h1>
<span>Chương 6 & 7</span>
</div>
<div class="layout">
<div class="sidebar">
<div class="sidebar-group">
<div class="sidebar-group-title">Sắp xếp</div>
<button class="sidebar-item active" onclick="loadAlgo('selection')">1. Chọn (Selection)</button>
<button class="sidebar-item" onclick="loadAlgo('insertion')">2. Chèn (Insertion)</button>
<button class="sidebar-item" onclick="loadAlgo('bubble')">3. Sủi bọt (Bubble)</button>
<button class="sidebar-item" onclick="loadAlgo('quick')">4. Nhanh (Quick)</button>
<button class="sidebar-item" onclick="loadAlgo('heap')">5. Vun đống (Heap)</button>
<button class="sidebar-item" onclick="loadAlgo('merge')">6. Trộn (Merge)</button>
</div>
<div class="sidebar-group">
<div class="sidebar-group-title">Tìm kiếm</div>
<button class="sidebar-item" onclick="loadAlgo('sequential')">7. Tuần tự</button>
<button class="sidebar-item" onclick="loadAlgo('binary')">8. Nhị phân</button>
<button class="sidebar-item" onclick="loadAlgo('bst')">9. Nhị phân trên cây</button>
</div>
</div>
<div class="main" id="main-area"></div>
</div>
<script>
const DEFAULTS = {
sort: [6,10,1,8,9,3,7,5,2,4],
search: [1,3,5,10,17,24,31],
bst: [8,10,19,3,21,7,5,12]
};
let state = {
algo: 'selection',
arr: [],
steps: [],
stepIdx: 0,
autoTimer: null,
speed: 400,
target: 5,
bstRoot: null,
bstSteps: [],
bstStepIdx: 0
};
const ALGOS = {
selection:{name:'Sắp xếp chọn',badge:'badge-sort',type:'sort'},
insertion:{name:'Sắp xếp chèn',badge:'badge-sort',type:'sort'},
bubble:{name:'Sắp xếp sủi bọt',badge:'badge-sort',type:'sort'},
quick:{name:'Sắp xếp nhanh',badge:'badge-sort',type:'sort'},
heap:{name:'Sắp xếp vun đống',badge:'badge-sort',type:'sort'},
merge:{name:'Sắp xếp trộn',badge:'badge-sort',type:'sort'},
sequential:{name:'Tìm kiếm tuần tự',badge:'badge-search',type:'search'},
binary:{name:'Tìm kiếm nhị phân',badge:'badge-search',type:'search'},
bst:{name:'Tìm kiếm nhị phân trên cây',badge:'badge-tree',type:'tree'}
};
function loadAlgo(algo){
state.algo=algo;
// Sửa lỗi ở đây: Duyệt qua các sidebar-item để set class active thay vì dùng event.target
document.querySelectorAll('.sidebar-item').forEach(b => {
b.classList.remove('active');
if(b.getAttribute('onclick') && b.getAttribute('onclick').includes(`loadAlgo('${algo}')`)) {
b.classList.add('active');
}
});
clearAuto();
render();
}
function render(){
const a=ALGOS[state.algo];
const isSearch=a.type==='search';
const isTree=a.type==='tree';
const defArr=isTree?DEFAULTS.bst:(isSearch?DEFAULTS.search:DEFAULTS.sort);
if(!state.arr.length||state._lastAlgo!==state.algo){
state.arr=[...defArr];
state._lastAlgo=state.algo;
state.steps=[];
state.stepIdx=0;
state.target=isSearch?5:undefined;
}
document.getElementById('main-area').innerHTML=buildUI(a,isSearch,isTree);
attachEvents();
}
function buildUI(a,isSearch,isTree){
const ps=getPseudocode(state.algo);
return `
<div class="card">
<div class="card-header">
<h2>${a.name}</h2>
<span class="badge ${a.badge}">${a.type==='sort'?'Sort':a.type==='search'?'Search':'BST'}</span>
</div>
<div class="card-body">
<div class="input-row">
<label>Dãy khoá:</label>
<input type="text" class="input-array" id="inp-arr" value="${state.arr.join(',')}" placeholder="vd: 8,10,19,3,21">
${isSearch||isTree?`<label>x =</label><input type="number" class="input-x" id="inp-x" value="${state.target}">`:``}
</div>
<div class="input-row">
<button class="btn btn-primary" onclick="genSteps()">▶ Tạo bước</button>
<button class="btn btn-step" onclick="nextStep()" id="btn-next">→ Bước tiếp</button>
<button class="btn btn-auto" onclick="toggleAuto()" id="btn-auto">⚡ Tự động</button>
<button class="btn btn-reset" onclick="resetSteps()">↺ Reset</button>
<div class="speed-row">
<span>Tốc độ:</span>
<input type="range" min="100" max="1500" value="${state.speed}" step="100" oninput="state.speed=+this.value">
</div>
</div>
<div id="viz-area">${buildViz()}</div>
<div class="stat-row" id="stat-row"></div>
<div id="result-area"></div>
<div class="steps-log" id="steps-log"><em style="color:#aaa">Nhấn "Tạo bước" để bắt đầu...</em></div>
</div>
</div>
<div class="card">
<div class="card-header"><h2>Giả mã (Pseudocode)</h2></div>
<div class="card-body">
<div class="pseudocode" id="ps-box">${ps}</div>
<div style="margin-top:12px;font-size:12px;color:#888">
${getComplexity(state.algo)}
</div>
</div>
</div>`;
}
function buildViz(){
if(state.algo==='bst') return `<canvas class="tree-canvas" id="tree-canvas" height="260"></canvas>`;
const arr=state.arr;
const maxV=Math.max(...arr,1);
const step=state.steps[state.stepIdx]||{};
const active=step.active||[];
const sorted=step.sorted||[];
const pivot=step.pivot!=null?[step.pivot]:[];
let html=`<div class="array-viz">`;
arr.forEach((v,i)=>{
const h=Math.max(10,Math.round((v/maxV)*80));
let cls='arr-bar';
if(sorted.includes(i))cls+=' sorted';
else if(active.includes(i))cls+=' active';
if(pivot.includes(i))cls=' arr-bar pivot';
if(step.found===i)cls=' arr-bar found';
html+=`<div class="arr-cell">
<div class="${cls}" style="height:${h}px" title="${v}"></div>
<div class="arr-label">${v}</div>
<div class="arr-idx">${i+1}</div>
</div>`;
});
html+=`</div>`;
return html;
}
function attachEvents(){}
function getArrInput(){
const raw=document.getElementById('inp-arr')?.value||'';
return raw.split(',').map(s=>parseInt(s.trim())).filter(n=>!isNaN(n));
}
function getXInput(){
return parseInt(document.getElementById('inp-x')?.value)||0;
}
function genSteps(){
clearAuto();
const arr=getArrInput();
if(!arr.length){alert('Nhập dãy khoá hợp lệ!');return;}
state.arr=[...arr];
state.target=getXInput();
state.steps=[];
state.stepIdx=0;
const algo=state.algo;
if(algo==='selection') genSelection([...arr]);
else if(algo==='insertion') genInsertion([...arr]);
else if(algo==='bubble') genBubble([...arr]);
else if(algo==='quick') genQuick([...arr]);
else if(algo==='heap') genHeap([...arr]);
else if(algo==='merge') genMerge([...arr]);
else if(algo==='sequential') genSequential([...arr],state.target);
else if(algo==='binary') genBinary([...arr],state.target);
else if(algo==='bst'){genBST([...arr],state.target);return;}
renderStep();
}
/* ---- SORT ALGORITHMS ---- */
function genSelection(a){
const n=a.length;
const steps=[];
for(let i=0;i<n-1;i++){
let k=i;
for(let j=i+1;j<n;j++){
steps.push({arr:[...a],active:[k,j],sorted:[...Array(i).keys()],msg:`i=${i+1}: so sánh a[${j+1}]=${a[j]} với a[${k+1}]=${a[k]}`});
if(a[j]<a[k])k=j;
}
if(k!==i){[a[i],a[k]]=[a[k],a[i]];steps.push({arr:[...a],active:[i,k],sorted:[...Array(i+1).keys()],msg:`Đổi chỗ a[${i+1}] ↔ a[${k+1}], vị trí ${i+1} đã sắp`});}
else steps.push({arr:[...a],active:[i],sorted:[...Array(i+1).keys()],msg:`a[${i+1}]=${a[i]} đã ở vị trí đúng`});
}
steps.push({arr:[...a],active:[],sorted:[...Array(n).keys()],msg:'✓ Sắp xếp hoàn thành!'});
state.steps=steps;
}
function genInsertion(a){
const n=a.length;
const steps=[];
for(let i=1;i<n;i++){
let tg=a[i],j=i-1;
steps.push({arr:[...a],active:[i],sorted:[...Array(i).keys()],msg:`i=${i+1}: lấy tg=a[${i+1}]=${tg}, chèn vào dãy đích`});
while(j>=0&&tg<a[j]){
a[j+1]=a[j];
steps.push({arr:[...a],active:[j,j+1],sorted:[...Array(i).keys()],msg:`tg=${tg} < a[${j+1}]=${a[j]}: dịch a[${j+1}] sang phải`});
j--;
}
a[j+1]=tg;
steps.push({arr:[...a],active:[j+1],sorted:[...Array(i+1).keys()],msg:`Chèn tg=${tg} vào vị trí ${j+2}`});
}
steps.push({arr:[...a],active:[],sorted:[...Array(n).keys()],msg:'✓ Sắp xếp hoàn thành!'});
state.steps=steps;
}
function genBubble(a){
const n=a.length;
const steps=[];
const sortedSet=new Set();
for(let i=0;i<n-1;i++){
for(let j=n-1;j>i;j--){
steps.push({arr:[...a],active:[j,j-1],sorted:[...sortedSet],msg:`So sánh a[${j}]=${a[j-1]} và a[${j+1}]=${a[j]}`});
if(a[j]<a[j-1]){[a[j],a[j-1]]=[a[j-1],a[j]];steps.push({arr:[...a],active:[j,j-1],sorted:[...sortedSet],msg:`Đổi chỗ a[${j}] ↔ a[${j+1}]`});}
}
sortedSet.add(i);
steps.push({arr:[...a],active:[i],sorted:[...sortedSet],msg:`Lượt ${i+1}: a[${i+1}]=${a[i]} đã vào vị trí`});
}
sortedSet.add(n-1);
steps.push({arr:[...a],active:[],sorted:[...sortedSet],msg:'✓ Sắp xếp hoàn thành!'});
state.steps=steps;
}
function genQuick(a){
const steps=[];
function qs(arr,L,R){
if(L>=R)return;
let i=L,j=R,k=Math.floor((L+R)/2),x=arr[k];
steps.push({arr:[...arr],active:[i,j],pivot:k,sorted:[],msg:`quickSort(L=${L+1},R=${R+1}): chọn pivot x=a[${k+1}]=${x}`});
do{
while(arr[i]<x)i++;
while(arr[j]>x)j--;
if(i<j){
steps.push({arr:[...arr],active:[i,j],pivot:k,sorted:[],msg:`a[${i+1}]=${arr[i]} >= x, a[${j+1}]=${arr[j]} <= x → đổi chỗ`});
[arr[i],arr[j]]=[arr[j],arr[i]];
steps.push({arr:[...arr],active:[i,j],pivot:k,sorted:[],msg:`Đổi a[${i+1}] ↔ a[${j+1}]`});
i++;j--;
}else if(i===j){i++;j--;}
}while(i<=j);
steps.push({arr:[...arr],active:[],pivot:-1,sorted:[],msg:`Phân đoạn xong: trái [${L+1}..${j+1}], phải [${i+1}..${R+1}]`});
qs(arr,L,j);
qs(arr,i,R);
}
const a2=[...a];
qs(a2,0,a2.length-1);
steps.push({arr:[...a2],active:[],sorted:[...Array(a2.length).keys()],msg:'✓ Sắp xếp hoàn thành!'});
state.steps=steps;
}
function genHeap(a){
const steps=[];
const n=a.length;
function adjust(arr,i,m){
let key=arr[i],j=2*i+1;
while(j<m){
if(j+1<m&&arr[j]<arr[j+1])j++;
steps.push({arr:[...arr],active:[i,j],sorted:[],msg:`adjust(${i+1},${m}): so sánh cha a[${i+1}]=${key} với con lớn nhất a[${j+1}]=${arr[j]}`});
if(key>arr[j]){arr[Math.floor((j-1)/2)]=key;return;}
arr[Math.floor((j-1)/2)]=arr[j];j=2*j+1;
}
arr[Math.floor((j-1)/2)]=key;
}
const arr=[...a];
steps.push({arr:[...arr],active:[],sorted:[],msg:'Giai đoạn 1: Tạo đống ban đầu'});
for(let i=Math.floor(n/2)-1;i>=0;i--){
adjust(arr,i,n);
steps.push({arr:[...arr],active:[i],sorted:[],msg:`Vun đống cây con gốc ${i+1}`});
}
steps.push({arr:[...arr],active:[0],sorted:[],msg:`Đống ban đầu xong. Gốc = ${arr[0]} (lớn nhất)`});
const sortedIdx=[];
for(let i=n-1;i>=1;i--){
steps.push({arr:[...arr],active:[0,i],sorted:[...sortedIdx],msg:`Đổi gốc a[1]=${arr[0]} với a[${i+1}]=${arr[i]}`});
[arr[0],arr[i]]=[arr[i],arr[0]];
sortedIdx.push(i);
steps.push({arr:[...arr],active:[0],sorted:[...sortedIdx],msg:`Loại nút ${i+1}, vun đống lại với ${i} nút`});
adjust(arr,0,i);
}
sortedIdx.push(0);
steps.push({arr:[...arr],active:[],sorted:[...Array(n).keys()],msg:'✓ Sắp xếp hoàn thành!'});
state.steps=steps;
}
function genMerge(a){
const steps=[];
const n=a.length;
let cur=[...a];
let L=1;
while(L<n){
let nxt=[...cur];
let i=0;
steps.push({arr:[...cur],active:[],sorted:[],msg:`MPass: L=${L}, trộn từng cặp dãy con dài ${L}`});
while(i<n){
const b=i,m=Math.min(i+L-1,n-1),r=Math.min(i+2*L-1,n-1);
if(m<r){
steps.push({arr:[...cur],active:[...Array(r-b+1).keys()].map(x=>x+b),sorted:[],msg:`Trộn [${b+1}..${m+1}] với [${m+2}..${r+1}]`});
let p=b,q=m+1,k=b,tmp=[...nxt];
while(p<=m&&q<=r){if(cur[p]<=cur[q])tmp[k++]=cur[p++];else tmp[k++]=cur[q++];}
while(p<=m)tmp[k++]=cur[p++];
while(q<=r)tmp[k++]=cur[q++];
nxt=tmp;
steps.push({arr:[...nxt],active:[...Array(r-b+1).keys()].map(x=>x+b),sorted:[],msg:`Sau trộn: [${nxt.slice(b,r+1).join(',')}]`});
}
i+=2*L;
}
cur=nxt;
L*=2;
}
steps.push({arr:[...cur],active:[],sorted:[...Array(n).keys()],msg:'✓ Sắp xếp hoàn thành!'});
state.steps=steps;
}
/* ---- SEARCH ALGORITHMS ---- */
function genSequential(a,x){
const steps=[];
const n=a.length;
for(let i=0;i<n;i++){
steps.push({arr:[...a],active:[i],sorted:[],msg:`Bước ${i+1}: so sánh k[${i+1}]=${a[i]} với x=${x}`});
if(a[i]===x){steps.push({arr:[...a],found:i,active:[i],sorted:[],msg:`✓ Tìm thấy x=${x} tại vị trí ${i+1}`});state.steps=steps;return;}
}
steps.push({arr:[...a],active:[],sorted:[],msg:`✗ Không tìm thấy x=${x} trong dãy khoá`});
state.steps=steps;
}
function genBinary(a,x){
const steps=[];
const sorted=[...a].sort((p,q)=>p-q);
if(JSON.stringify(a)!==JSON.stringify(sorted)){
steps.push({arr:[...a],active:[],sorted:[],msg:'⚠ Dãy cần được sắp xếp tăng dần trước khi tìm nhị phân!'});
state.steps=steps;return;
}
let L=0,R=a.length-1;
while(L<=R){
const m=Math.floor((L+R)/2);
steps.push({arr:[...a],active:[L,R,m],sorted:[],msg:`L=${L+1}, R=${R+1}, m=${m+1}: so sánh k[${m+1}]=${a[m]} với x=${x}`});
if(x===a[m]){steps.push({arr:[...a],found:m,active:[m],sorted:[],msg:`✓ Tìm thấy x=${x} tại vị trí ${m+1}`});state.steps=steps;return;}
else if(x<a[m]){steps.push({arr:[...a],active:[L,m-1],sorted:[],msg:`x=${x} < k[${m+1}]=${a[m]}: tìm nửa trái [${L+1}..${m}]`});R=m-1;}
else{steps.push({arr:[...a],active:[m+1,R],sorted:[],msg:`x=${x} > k[${m+1}]=${a[m]}: tìm nửa phải [${m+2}..${R+1}]`});L=m+1;}
}
steps.push({arr:[...a],active:[],sorted:[],msg:`✗ Không tìm thấy x=${x}`});
state.steps=steps;
}
/* ---- BST ---- */
class BSTNode{constructor(k){this.key=k;this.left=null;this.right=null;this.x=0;this.y=0;}}
function genBST(keys,x){
state.bstSteps=[];
state.bstStepIdx=0;
let root=null;
const insertLog=[];
for(const k of keys){
const r=bstInsert(root,k);
root=r.root;
insertLog.push(...r.log);
}
state.bstRoot=root;
const searchLog=bstSearch(root,x);
state.bstSteps=[
{phase:'build',log:insertLog,highlight:[],root:cloneTree(root),msg:'Đã xây dựng cây nhị phân tìm kiếm'},
...searchLog
];
state.bstStepIdx=0;
renderBSTStep();
}
function bstInsert(root,k){
const log=[];
let p=null,q=root;
while(q!==null){
log.push({compare:q.key,path:k});
p=q;
if(k<q.key)q=q.left;
else if(k>q.key)q=q.right;
else return{root,log};
}
const node=new BSTNode(k);
if(!p)root=node;
else if(k<p.key)p.left=node;
else p.right=node;
return{root,log};
}
function bstSearch(root,x){
const steps=[];
let q=root;
const path=[];
while(q!==null){
path.push(q.key);
steps.push({phase:'search',highlight:[...path],current:q.key,msg:`So sánh x=${x} với khoá ${q.key}`});
if(x===q.key){steps.push({phase:'found',highlight:[...path],current:q.key,msg:`✓ Tìm thấy x=${x} trên cây!`});return steps;}
else if(x<q.key){steps.push({phase:'search',highlight:[...path],msg:`x=${x} < ${q.key}: rẽ trái`});q=q.left;}
else{steps.push({phase:'search',highlight:[...path],msg:`x=${x} > ${q.key}: rẽ phải`});q=q.right;}
}
steps.push({phase:'notfound',highlight:[...path],msg:`✗ Không tìm thấy x=${x}, cây rỗng → bổ sung x`});
return steps;
}
function cloneTree(node){if(!node)return null;const n=new BSTNode(node.key);n.left=cloneTree(node.left);n.right=cloneTree(node.right);return n;}
function layoutTree(node,x,y,dx){
if(!node)return;
node.x=x;node.y=y;
layoutTree(node.left,x-dx,y+60,dx/2);
layoutTree(node.right,x+dx,y+60,dx/2);
}
function renderBSTStep(){
const canvas=document.getElementById('tree-canvas');
if(!canvas)return;
const ctx=canvas.getContext('2d');
const W=canvas.offsetWidth||600;
canvas.width=W;canvas.height=260;
ctx.clearRect(0,0,W,260);
const root=state.bstRoot;
if(!root)return;
layoutTree(root,W/2,36,W/4);
const step=state.bstSteps[state.bstStepIdx]||{highlight:[],current:null};
const hl=new Set(step.highlight||[]);
drawTree(ctx,root,hl,step.current,step.phase);
const log=document.getElementById('steps-log');
if(log){
let html='';
state.bstSteps.slice(0,state.bstStepIdx+1).forEach((s,i)=>{
html+=`<div class="step-entry">${i===state.bstStepIdx?'→ ':''}${s.msg}</div>`;
});
log.innerHTML=html;
log.scrollTop=log.scrollHeight;
}
const ra=document.getElementById('result-area');
if(ra&&step.phase){
if(step.phase==='found')ra.innerHTML=`<div class="result-box result-ok">✓ Tìm thấy x=${state.target} trên cây!</div>`;
else if(step.phase==='notfound')ra.innerHTML=`<div class="result-box result-err">✗ Không tìm thấy — bổ sung x=${state.target} vào cây</div>`;
else ra.innerHTML='';
}
}
function drawTree(ctx,node,hl,cur,phase){
if(!node)return;
if(node.left){
ctx.beginPath();ctx.moveTo(node.x,node.y);ctx.lineTo(node.left.x,node.left.y);
ctx.strokeStyle='#ccc';ctx.lineWidth=1.5;ctx.stroke();
}
if(node.right){
ctx.beginPath();ctx.moveTo(node.x,node.y);ctx.lineTo(node.right.x,node.right.y);
ctx.strokeStyle='#ccc';ctx.lineWidth=1.5;ctx.stroke();
}
drawTree(ctx,node.left,hl,cur,phase);
drawTree(ctx,node.right,hl,cur,phase);
const r=18;
let fill='#e0dff7';let stroke='#5b4fcf';let txtColor='#1a1a2e';
if(node.key===cur&&phase==='found'){fill='#d1fae5';stroke='#10b981';txtColor='#065f46';}
else if(node.key===cur){fill='#fef3c7';stroke='#f59e0b';txtColor='#92400e';}
else if(hl.has(node.key)){fill='#ede9fe';stroke='#7c3aed';}
ctx.beginPath();ctx.arc(node.x,node.y,r,0,Math.PI*2);
ctx.fillStyle=fill;ctx.fill();ctx.strokeStyle=stroke;ctx.lineWidth=2;ctx.stroke();
ctx.fillStyle=txtColor;ctx.font='500 12px system-ui';ctx.textAlign='center';ctx.textBaseline='middle';
ctx.fillText(node.key,node.x,node.y);
}
/* ---- STEP CONTROL ---- */
function nextStep(){
if(state.algo==='bst'){
if(state.bstStepIdx<state.bstSteps.length-1){state.bstStepIdx++;renderBSTStep();}
return;
}
if(!state.steps.length){genSteps();return;}
if(state.stepIdx<state.steps.length-1){state.stepIdx++;renderStep();}
}
function resetSteps(){
clearAuto();
state.steps=[];state.stepIdx=0;
state.bstSteps=[];state.bstStepIdx=0;
state.arr=getArrInput();
state.target=getXInput();
renderViz();
const log=document.getElementById('steps-log');
if(log)log.innerHTML='<em style="color:#aaa">Nhấn "Tạo bước" để bắt đầu...</em>';
const ra=document.getElementById('result-area');
if(ra)ra.innerHTML='';
}
function toggleAuto(){
if(state.autoTimer){clearAuto();document.getElementById('btn-auto').textContent='⚡ Tự động';return;}
document.getElementById('btn-auto').textContent='⏸ Dừng';
function tick(){
const isLast=state.algo==='bst'?state.bstStepIdx>=state.bstSteps.length-1:state.stepIdx>=state.steps.length-1;
if(isLast){clearAuto();document.getElementById('btn-auto').textContent='⚡ Tự động';return;}
nextStep();
state.autoTimer=setTimeout(tick,state.speed);
}
if(state.algo==='bst'?!state.bstSteps.length:!state.steps.length)genSteps();
tick();
}
function clearAuto(){clearTimeout(state.autoTimer);state.autoTimer=null;}
function renderStep(){
if(!state.steps.length)return;
const step=state.steps[state.stepIdx];
if(step.arr)state.arr=[...step.arr];
renderViz(step);
const log=document.getElementById('steps-log');
if(log){
let html='';
state.steps.slice(0,state.stepIdx+1).forEach((s,i)=>{
html+=`<div class="step-entry">${i===state.stepIdx?'→ ':''}${s.msg}</div>`;
});
log.innerHTML=html;log.scrollTop=log.scrollHeight;
}
const ra=document.getElementById('result-area');
if(ra){
if(step.found!=null)ra.innerHTML=`<div class="result-box result-ok">✓ Tìm thấy x=${state.target} tại vị trí ${step.found+1}</div>`;
else if(state.stepIdx===state.steps.length-1&&step.msg.includes('✗'))ra.innerHTML=`<div class="result-box result-err">${step.msg}</div>`;
else if(state.stepIdx===state.steps.length-1&&step.msg.includes('✓'))ra.innerHTML=`<div class="result-box result-ok">${step.msg}</div>`;
else ra.innerHTML='';
}
const sr=document.getElementById('stat-row');
if(sr){
sr.innerHTML=`
<div class="stat"><div class="stat-val">${state.stepIdx+1}/${state.steps.length}</div><div class="stat-lbl">Bước</div></div>
<div class="stat"><div class="stat-val">${Math.round((state.stepIdx/(state.steps.length-1||1))*100)}%</div><div class="stat-lbl">Tiến độ</div></div>`;
}
}
function renderViz(step){
const va=document.getElementById('viz-area');
if(!va)return;
if(state.algo==='bst'){renderBSTStep();return;}
const arr=state.arr;
const maxV=Math.max(...arr,1);
const s=step||{};
let html=`<div class="array-viz">`;
arr.forEach((v,i)=>{
const h=Math.max(10,Math.round((v/maxV)*80));
let cls='arr-bar';
const sorted=s.sorted||[];
const active=s.active||[];
if(sorted.includes(i))cls+=' sorted';
else if(active.includes(i))cls+=' active';
if(s.pivot===i)cls=' arr-bar pivot';
if(s.found===i)cls=' arr-bar found';
html+=`<div class="arr-cell">
<div class="${cls}" style="height:${h}px"></div>
<div class="arr-label">${v}</div>
<div class="arr-idx">${i+1}</div>
</div>`;
});
html+=`</div>`;
va.innerHTML=html;
}
/* ---- PSEUDOCODE ---- */
function getPseudocode(algo){
const codes={
selection:`<span class="ps-fn">Procedure</span> selectionSort(a, n)
<span class="ps-kw">For</span> i := 1 <span class="ps-kw">to</span> n-1 <span class="ps-kw">Do</span>
<span class="ps-cmt">{ Tìm vị trí k của phần tử nhỏ nhất }</span>
k := i
<span class="ps-kw">For</span> j := i+1 <span class="ps-kw">To</span> n <span class="ps-kw">Do</span>
<span class="ps-kw">If</span> a[j] < a[k] <span class="ps-kw">then</span> k := j
<span class="ps-cmt">{ Đổi chỗ phần tử nhỏ nhất ở vị trí k cho i }</span>
<span class="ps-kw">If</span> k ≠ i <span class="ps-kw">then</span> a[k] ↔ a[i]
<span class="ps-kw">Return</span>`,
insertion:`<span class="ps-fn">Procedure</span> insertSort(a, n)
a[0] := -∞ <span class="ps-cmt">{ lính canh }</span>
<span class="ps-kw">For</span> i := 2 <span class="ps-kw">to</span> n <span class="ps-kw">Do</span>
tg := a[i]; j := i-1
<span class="ps-kw">While</span> tg < a[j] <span class="ps-kw">Do</span>
a[j+1] := a[j]; j := j-1
a[j+1] := tg <span class="ps-cmt">{ chèn tg vào đúng vị trí }</span>
<span class="ps-kw">Return</span>`,
bubble:`<span class="ps-fn">Procedure</span> bubbleSort(a, n)
<span class="ps-kw">For</span> i := 1 <span class="ps-kw">to</span> n-1 <span class="ps-kw">Do</span>
<span class="ps-kw">For</span> j := n <span class="ps-kw">downto</span> i+1 <span class="ps-kw">Do</span>
<span class="ps-kw">If</span> a[j] < a[j-1] <span class="ps-kw">then</span>
a[j] ↔ a[j-1]
<span class="ps-kw">Return</span>`,
quick:`<span class="ps-fn">Procedure</span> quickSort(L, R)
1. <span class="ps-kw">If</span> L >= R <span class="ps-kw">then return</span>
2. i := L; j := R; k := (L+R) div 2
3. x := a[k] <span class="ps-cmt">{ chọn phần tử giữa làm pivot }</span>
4. <span class="ps-kw">Repeat</span>
<span class="ps-kw">While</span> a[i] < x <span class="ps-kw">Do</span> i := i+1
<span class="ps-kw">While</span> a[j] > x <span class="ps-kw">Do</span> j := j-1
<span class="ps-kw">If</span> i < j <span class="ps-kw">then</span> a[i] ↔ a[j]
<span class="ps-kw">Until</span> i = j
5. <span class="ps-kw">Call</span> quickSort(L, j-1)
6. <span class="ps-kw">Call</span> quickSort(j+1, R)
<span class="ps-kw">Return</span>`,
heap:`<span class="ps-fn">Procedure</span> heapSort(a, n)
<span class="ps-cmt">{ Giai đoạn 1: Tạo đống ban đầu }</span>
<span class="ps-kw">For</span> i := n div 2 <span class="ps-kw">Downto</span> 1 <span class="ps-kw">Do</span>
<span class="ps-kw">Call</span> adjust(i, n)
<span class="ps-cmt">{ Giai đoạn 2: Sắp xếp }</span>
<span class="ps-kw">For</span> i := n-1 <span class="ps-kw">Downto</span> 1 <span class="ps-kw">Do</span>
tg := a[1]; a[1] := a[i+1]; a[i+1] := tg
<span class="ps-kw">Call</span> adjust(1, i)
<span class="ps-kw">Return</span>`,
merge:`<span class="ps-fn">Procedure</span> mergeSort(a, n)
1. L := 1
2. <span class="ps-kw">While</span> L < n <span class="ps-kw">Do</span>
<span class="ps-kw">Call</span> MPass(a, b, n, L); L := L+L
<span class="ps-kw">Call</span> MPass(b, a, n, L); L := L+L
<span class="ps-kw">Return</span>
<span class="ps-fn">Procedure</span> merge(X, b, m, n, Z)
i:=k:=b; j:=m+1
<span class="ps-kw">While</span> (i<=m) <span class="ps-kw">and</span> (j<=n) <span class="ps-kw">Do</span>
<span class="ps-kw">If</span> X[i] <= X[j] <span class="ps-kw">then</span> Z[k]:=X[i]; i:=i+1
<span class="ps-kw">Else</span> Z[k]:=X[j]; j:=j+1
k:=k+1
<span class="ps-cmt">{ Đưa nốt dãy còn lại }</span>`,
sequential:`<span class="ps-fn">Function</span> sequenceSearch(k, n, x)
1. <span class="ps-cmt">{ Khởi tạo }</span>
i := 1; k[n+1] := x <span class="ps-cmt">{ lính canh cuối }</span>
2. <span class="ps-cmt">{ Tìm kiếm trong dãy }</span>
<span class="ps-kw">While</span> k[i] ≠ x <span class="ps-kw">Do</span> i := i+1
3. <span class="ps-cmt">{ Trả về kết quả }</span>
<span class="ps-kw">If</span> i = n+1 <span class="ps-kw">then Return</span>(0)
<span class="ps-kw">Else Return</span>(i)`,
binary:`<span class="ps-fn">Function</span> binarySearch(k, n, x)
1. L := 1; R := n
2. <span class="ps-kw">While</span> L <= R <span class="ps-kw">Do</span>
m := (L+R) div 2
<span class="ps-kw">If</span> x < k[m] <span class="ps-kw">then</span> R := m-1
<span class="ps-kw">Else If</span> x > k[m] <span class="ps-kw">then</span> L := m+1
<span class="ps-kw">Else Return</span>(m)
3. <span class="ps-kw">Return</span>(0) <span class="ps-cmt">{ không tìm thấy }</span>`,
bst:`<span class="ps-fn">Function</span> BST(Var T; x)
1. <span class="ps-cmt">{ Khởi tạo con trỏ }</span>
p := Null; q := T
2. <span class="ps-cmt">{ Tìm kiếm }</span>
<span class="ps-kw">While</span> q ≠ Null <span class="ps-kw">Do</span>
<span class="ps-kw">Case</span>
x < key(q): p:=q; q:=left(q)
x = key(q): <span class="ps-kw">Return</span>(q)
x > key(q): p:=q; q:=right(q)
<span class="ps-kw">End Case</span>
3. <span class="ps-cmt">{ Bổ sung }</span>
q ⇐ AVAIL; key(q):=x
left(q):=right(q):= Null
<span class="ps-kw">Case</span>
T=Null: T:=q
x < key(p): left(p):=q
Else: right(p):=q
<span class="ps-kw">End case</span>
<span class="ps-kw">Return</span>(q)`
};
return codes[algo]||'';
}
function getComplexity(algo){
const c={
selection:'<b>O(n²)</b> — C<sub>min</sub>=C<sub>max</sub>=C<sub>tb</sub>=n(n-1)/2',
insertion:'<b>O(n²)</b> — C<sub>min</sub>=n-1 | C<sub>max</sub>=n(n-1)/2 | C<sub>tb</sub>=(n²+n-2)/4',
bubble:'<b>O(n²)</b> — C<sub>min</sub>=C<sub>max</sub>=n(n-1)/2',
quick:'<b>T<sub>tb</sub> = O(n·log₂n)</b> — tốt hơn 3 phương pháp trên khi n lớn',
heap:'<b>O(n·log₂n)</b> — hiệu quả cho n lớn',
merge:'<b>T<sub>tb</sub> = O(n·log₂n)</b> — ổn định, phù hợp dãy có sắp một phần',
sequential:'<b>O(n)</b> — C<sub>min</sub>=1 | C<sub>max</sub>=n+1 | C<sub>tb</sub>=(n+1)/2',
binary:'<b>O(log₂n)</b> — C<sub>min</sub>=1 | C<sub>max</sub>=[log₂n]+1 — yêu cầu dãy đã sắp',
bst:'<b>O(log₂n)</b> — yêu cầu cây nhị phân tìm kiếm hợp lệ'
};
return c[algo]||'';
}
loadAlgo('selection');
</script>
</body>
</html>