-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmerge-sort.html
More file actions
836 lines (726 loc) · 36.6 KB
/
Copy pathmerge-sort.html
File metadata and controls
836 lines (726 loc) · 36.6 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
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>归并排序可视化 | Merge Sort Pro</title>
<link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
<style>
@import url('https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;700&family=Inter:wght@300;400;500;600;700&display=swap');
:root {
--primary: #4f46e5;
--secondary: #8b5cf6;
--bg-gradient: linear-gradient(135deg, #f8fafc 0%, #e0e7ff 100%);
/* 归并排序特有变量 */
--block-size: 48px;
--level-height: 100px;
--gap-x: 12px;
}
body {
font-family: 'Inter', sans-serif;
background: var(--bg-gradient);
color: #334155;
min-height: 100vh;
overflow-x: hidden;
}
/* 玻璃拟态效果 */
.glass-card {
background: rgba(255, 255, 255, 0.9);
backdrop-filter: blur(12px);
border: 1px solid rgba(255, 255, 255, 0.8);
box-shadow: 0 10px 30px -5px rgba(0, 0, 0, 0.06);
transition: all 0.3s ease;
}
/* 归并排序舞台 */
.viz-stage {
position: relative;
width: 100%;
height: 520px; /* 足够容纳递归层级 */
overflow: hidden; /* 隐藏溢出,或者改为 visible 视情况而定 */
background-image: radial-gradient(#cbd5e1 1px, transparent 1px);
background-size: 24px 24px;
border-radius: 1rem;
transition: height 0.3s ease;
}
/* 数组方块元素 */
.array-item {
position: absolute;
width: var(--block-size);
height: var(--block-size);
display: flex;
align-items: center;
justify-content: center;
border-radius: 10px;
font-family: 'JetBrains Mono', monospace;
font-weight: 800;
font-size: 16px;
background-color: white;
border: 2px solid #cbd5e1;
color: #475569;
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
transition: top 0.5s cubic-bezier(0.25, 1, 0.5, 1),
left 0.5s cubic-bezier(0.25, 1, 0.5, 1),
transform 0.3s, background-color 0.3s, border-color 0.3s, box-shadow 0.3s;
z-index: 10;
will-change: top, left;
}
/* 连线效果 (伪元素) */
.array-item::before {
content: '';
position: absolute;
top: -40px;
left: 50%;
width: 2px;
height: 40px;
background: #e2e8f0;
transform: translateX(-50%);
opacity: 0;
transition: opacity 0.3s;
z-index: -1;
}
.item-deep .array-item::before { opacity: 1; }
/* 状态颜色系统 */
.color-default { background-color: white; border-color: #cbd5e1; }
/* 左区间 L */
.color-left {
background-color: #eff6ff !important;
border-color: #3b82f6 !important;
color: #1d4ed8 !important;
}
/* 右区间 R */
.color-right {
background-color: #fdf4ff !important;
border-color: #d946ef !important;
color: #a21caf !important;
}
/* 比较中/高亮 */
.color-comparing {
transform: scale(1.15);
z-index: 50;
border-color: #f59e0b !important; /* Amber */
box-shadow: 0 10px 25px rgba(245, 158, 11, 0.3) !important;
}
/* 已归并/排序完成 */
.color-sorted {
background-color: #ecfdf5 !important;
border-color: #10b981 !important;
color: #047857 !important;
box-shadow: 0 4px 10px rgba(16, 185, 129, 0.2) !important;
}
/* 指针系统 (保留选择排序风格的Tag) */
.pointer-container {
position: absolute;
top: 0; left: 0; width: 100%; height: 100%;
pointer-events: none;
overflow: visible;
}
.pointer {
position: absolute;
transition: top 0.5s cubic-bezier(0.25, 1, 0.5, 1), left 0.5s cubic-bezier(0.25, 1, 0.5, 1);
display: flex;
flex-direction: column;
align-items: center;
z-index: 40;
width: 40px;
height: 50px;
}
.pointer-tag {
font-size: 10px;
font-weight: 800;
padding: 3px 6px;
border-radius: 4px;
color: white;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
margin-top: 2px;
text-transform: uppercase;
}
.pointer-arrow {
width: 0;
height: 0;
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-bottom: 6px solid; /* 向上箭头 */
}
/* L 指针 (Blue) */
.pointer-l .pointer-tag { background-color: #3b82f6; }
.pointer-l .pointer-arrow { border-bottom-color: #3b82f6; }
/* R 指针 (Fuchsia) */
.pointer-r .pointer-tag { background-color: #d946ef; }
.pointer-r .pointer-arrow { border-bottom-color: #d946ef; }
/* 终端日志 */
.log-container {
font-family: 'JetBrains Mono', monospace;
background: #f1f5f9;
border: 1px solid #e2e8f0;
border-left: 4px solid #4f46e5;
}
.log-entry { animation: fadeIn 0.3s ease; }
@keyframes fadeIn { from { opacity: 0; transform: translateY(5px); } to { opacity: 1; transform: 0; } }
/* 布局控制 */
.layout-default .main-grid { display: flex; flex-direction: column; gap: 1.5rem; }
.layout-sidebar .main-grid { display: grid; grid-template-columns: 1fr 350px; gap: 1.5rem; }
@media (max-width: 1024px) { .layout-sidebar .main-grid { grid-template-columns: 1fr; } }
/* 状态灯 */
.status-dot { width: 8px; height: 8px; border-radius: 50%; display: inline-block; margin-right: 6px; }
.dot-running { background: #10b981; animation: pulse 1.5s infinite; }
.dot-paused { background: #f59e0b; }
.dot-idle { background: #94a3b8; }
@keyframes pulse { 0% { opacity: 1; transform: scale(1); } 50% { opacity: 0.5; transform: scale(1.2); } 100% { opacity: 1; transform: scale(1); } }
/* 徽章 */
.badge { display: inline-flex; align-items: center; padding: 0.125rem 0.5rem; border-radius: 0.375rem; font-size: 0.75rem; font-weight: 600; }
.badge-worst { background-color: #fee2e2; color: #991b1b; }
.badge-stable { background-color: #d1fae5; color: #065f46; }
</style>
</head>
<body class="p-4 md:p-8">
<div class="max-w-7xl mx-auto">
<!-- Header -->
<header class="flex flex-col md:flex-row justify-between items-center mb-8 gap-4">
<div>
<div class="flex items-center gap-3 mb-1">
<div class="p-2 bg-indigo-600 rounded-xl text-white shadow-lg shadow-indigo-200 transform -rotate-3">
<i class="fas fa-layer-group fa-lg"></i>
</div>
<h1 class="text-3xl font-extrabold text-slate-800 tracking-tight">归并排序</h1>
</div>
<p class="text-slate-500 font-medium">Visualization of Merge Sort Algorithm</p>
</div>
<div class="flex gap-3">
<button id="layoutToggle" class="glass-card px-5 py-2.5 rounded-xl text-slate-700 font-semibold hover:bg-white transition flex items-center gap-2">
<i class="fas fa-columns text-indigo-500"></i> 视图切换
</button>
</div>
</header>
<div id="mainContent" class="layout-default">
<!-- Control Panel -->
<section class="glass-card rounded-2xl p-6 mb-6">
<div class="grid grid-cols-1 lg:grid-cols-4 gap-6 items-end">
<!-- Size Control -->
<div>
<div class="flex justify-between mb-2">
<label class="text-xs font-bold text-slate-500 uppercase">数组规模</label>
<span id="sizeValue" class="text-indigo-600 font-bold font-mono text-sm">8</span>
</div>
<input type="range" id="sizeSlider" min="4" max="16" value="8" class="w-full accent-indigo-600 cursor-pointer h-2 bg-slate-200 rounded-lg appearance-none">
</div>
<!-- Speed Control -->
<div>
<div class="flex justify-between mb-2">
<label class="text-xs font-bold text-slate-500 uppercase">动画速度</label>
<span id="speedValue" class="text-indigo-600 font-bold font-mono text-sm">3</span>
</div>
<input type="range" id="speedSlider" min="1" max="5" value="3" class="w-full accent-indigo-600 cursor-pointer h-2 bg-slate-200 rounded-lg appearance-none">
</div>
<!-- Custom Input -->
<div class="lg:col-span-1">
<label class="text-xs font-bold text-slate-500 uppercase block mb-2">自定义数据</label>
<input type="text" id="customArray" placeholder="例如: 8,3,5,4" class="w-full bg-slate-50 border border-slate-200 rounded-xl px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 transition shadow-sm font-mono">
</div>
<!-- Generate Button -->
<button id="generateBtn" class="bg-indigo-50 text-indigo-600 h-10 px-4 rounded-xl font-bold hover:bg-indigo-100 transition border border-indigo-100 flex items-center justify-center gap-2">
<i class="fas fa-sync-alt"></i> 生成数组
</button>
</div>
</section>
<div class="main-grid">
<!-- Left/Top Section: Visualization -->
<div class="space-y-6">
<section class="glass-card rounded-3xl p-6 relative flex flex-col">
<!-- Status Bar -->
<div class="flex justify-between items-center mb-4 pb-4 border-b border-slate-100 z-20">
<div class="flex items-center gap-4">
<span class="flex items-center text-sm font-bold text-slate-600 bg-white border border-slate-200 px-4 py-1.5 rounded-full shadow-sm">
<span id="statusIndicator" class="status-dot dot-idle"></span>
<span id="statusText">准备就绪</span>
</span>
</div>
<div class="flex items-center gap-2">
<span class="text-xs text-slate-400 font-bold uppercase">Comparisons</span>
<div id="compCount" class="font-mono text-xl font-bold text-indigo-600 bg-indigo-50 px-3 py-1 rounded-lg border border-indigo-100">
0
</div>
</div>
</div>
<!-- Visualization Container (Stage) -->
<div id="vizStage" class="viz-stage mb-6">
<!-- JS Generated Items -->
<div id="pointerLayer" class="pointer-container">
<!-- JS Generated Pointers -->
</div>
</div>
<!-- Controls -->
<div class="flex flex-wrap justify-center gap-3 z-20">
<button id="startBtn" class="group px-6 py-2.5 bg-indigo-600 text-white rounded-xl font-bold hover:bg-indigo-700 transition shadow-lg shadow-indigo-200 active:scale-95 flex items-center gap-2">
<i class="fas fa-play"></i> 开始归并
</button>
<button id="pauseBtn" disabled class="px-6 py-2.5 bg-white border border-slate-200 text-slate-700 rounded-xl font-bold hover:bg-slate-50 transition disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2">
<i class="fas fa-pause"></i> 暂停
</button>
<button id="stepBtn" disabled class="px-6 py-2.5 bg-white border border-slate-200 text-indigo-600 rounded-xl font-bold hover:bg-indigo-50 transition disabled:opacity-50 active:scale-95 flex items-center gap-2">
<i class="fas fa-step-forward"></i> 单步
</button>
<button id="resetBtn" class="px-6 py-2.5 bg-rose-50 border border-rose-100 text-rose-600 rounded-xl font-bold hover:bg-rose-100 transition active:scale-95 flex items-center gap-2">
<i class="fas fa-undo"></i> 重置
</button>
</div>
</section>
<!-- Terminal Log -->
<section class="log-container rounded-2xl p-4">
<div class="flex items-center justify-between mb-3 border-b border-slate-200 pb-2">
<div class="flex items-center gap-2 text-slate-700 text-xs font-bold uppercase tracking-widest">
<i class="fas fa-terminal text-indigo-500"></i> 执行日志
</div>
<button onclick="clearLog()" class="text-slate-400 hover:text-slate-600 text-xs"><i class="fas fa-trash"></i></button>
</div>
<div id="terminalLog" class="h-32 overflow-y-auto space-y-1.5 text-sm scrollbar-hide px-1">
<div class="text-slate-500 flex items-start gap-2">
<span class="text-indigo-400 font-bold">></span>
<span>等待系统指令...</span>
</div>
</div>
</section>
</div>
<!-- Right/Bottom Section: Algorithm Info -->
<aside id="infoSection" class="glass-card rounded-2xl p-6 border-t-4 border-indigo-500 h-full">
<div id="introContent">
<h3 class="text-lg font-bold text-slate-800 mb-6 flex items-center gap-2 pb-4 border-b border-slate-100">
<i class="fas fa-book-open text-indigo-500"></i> 算法详解
</h3>
<!-- Legend -->
<div class="mb-6 bg-slate-50 p-4 rounded-xl border border-slate-100">
<h4 class="text-xs font-bold text-slate-500 uppercase mb-3">图例说明</h4>
<div class="grid grid-cols-2 gap-3 text-xs font-medium text-slate-600">
<div class="flex items-center gap-2"><div class="w-3 h-3 rounded bg-blue-100 border border-blue-500"></div>左区间 (L)</div>
<div class="flex items-center gap-2"><div class="w-3 h-3 rounded bg-fuchsia-100 border border-fuchsia-500"></div>右区间 (R)</div>
<div class="flex items-center gap-2"><div class="w-3 h-3 rounded bg-white border border-amber-500 shadow-sm"></div>比较中</div>
<div class="flex items-center gap-2"><div class="w-3 h-3 rounded bg-emerald-100 border border-emerald-500"></div>已归并</div>
</div>
<div class="mt-3 pt-3 border-t border-slate-200 flex gap-4 text-xs">
<div class="flex items-center gap-1"><span class="bg-blue-500 text-white px-1.5 rounded">L</span> 左指针</div>
<div class="flex items-center gap-1"><span class="bg-fuchsia-500 text-white px-1.5 rounded">R</span> 右指针</div>
</div>
</div>
<!-- Algorithm Details -->
<div class="space-y-6 text-slate-600 text-sm">
<div>
<h4 class="font-bold text-slate-800 mb-2">💡 核心思想</h4>
<p class="leading-relaxed">分治法 (Divide and Conquer)。将数组不断二分直到只剩一个元素,然后两两合并(Merge)有序序列,最终得到有序数组。</p>
</div>
<div>
<h4 class="font-bold text-slate-800 mb-2">📊 复杂度分析</h4>
<div class="flex flex-wrap gap-2 mb-2">
<span class="badge badge-worst">时间: O(n log n)</span>
<span class="badge badge-worst">空间: O(n)</span>
</div>
<p class="text-xs text-slate-500">效率非常稳定,但需要额外的 O(n) 空间。</p>
</div>
<div>
<h4 class="font-bold text-slate-800 mb-2">⚖️ 稳定性</h4>
<span class="badge badge-stable mb-1">稳定</span>
<p class="text-xs text-slate-500 mt-1">相同值的元素在排序后相对位置不变。</p>
</div>
</div>
</div>
</aside>
</div>
</div>
<!-- Footer -->
<footer class="mt-8 text-center text-slate-400 text-xs pb-4">
<p>Designed with Tailwind CSS & Glassmorphism</p>
</footer>
</div>
<script>
// --- 全局配置与状态 ---
const config = {
blockSize: 48,
gapX: 12,
levelHeight: 100,
baseTop: 60,
speeds: [2000, 1200, 800, 400, 150]
};
let state = {
visualItems: [], // 存储 {id, value, el, currentIdx, depth}
arraySize: 8,
speed: 800,
isSorting: false,
isPaused: false,
isComplete: false,
stopFlag: false,
stepResolver: null,
comparisons: 0,
savedInitialData: [],
currentPointers: { l: null, r: null }
};
// --- DOM 元素 ---
const els = {
sizeSlider: document.getElementById('sizeSlider'),
sizeValue: document.getElementById('sizeValue'),
speedSlider: document.getElementById('speedSlider'),
speedValue: document.getElementById('speedValue'),
customInput: document.getElementById('customArray'),
genBtn: document.getElementById('generateBtn'),
startBtn: document.getElementById('startBtn'),
pauseBtn: document.getElementById('pauseBtn'),
stepBtn: document.getElementById('stepBtn'),
resetBtn: document.getElementById('resetBtn'),
stage: document.getElementById('vizStage'),
pointerLayer: document.getElementById('pointerLayer'),
log: document.getElementById('terminalLog'),
statusText: document.getElementById('statusText'),
statusDot: document.getElementById('statusIndicator'),
compCount: document.getElementById('compCount'),
layoutToggle: document.getElementById('layoutToggle'),
mainContent: document.getElementById('mainContent')
};
// --- 初始化 ---
document.addEventListener('DOMContentLoaded', () => {
initEventListeners();
generateArray(true);
setupResizeObserver();
});
function initEventListeners() {
// 布局切换
els.layoutToggle.addEventListener('click', toggleLayout);
// 滑块控制
els.sizeSlider.addEventListener('input', e => {
els.sizeValue.textContent = e.target.value;
state.arraySize = parseInt(e.target.value);
if (!state.isSorting) generateArray(true);
});
els.speedSlider.addEventListener('input', e => {
els.speedValue.textContent = e.target.value;
state.speed = config.speeds[e.target.value - 1];
});
// 按钮控制
els.genBtn.addEventListener('click', () => {
const val = els.customInput.value.trim();
if(val) {
const arr = val.split(/[,, ]+/).map(Number).filter(n => !isNaN(n));
if(arr.length > 1 && arr.length <= 16) {
state.arraySize = arr.length;
els.sizeSlider.value = arr.length;
els.sizeValue.textContent = arr.length;
createVisualItems(arr);
state.savedInitialData = [...arr];
resetState();
} else {
alert('请输入2-16个数字,用逗号分隔');
}
} else {
generateArray(true);
}
});
els.startBtn.addEventListener('click', () => {
if (state.isPaused && state.isSorting) togglePause();
else startSort();
});
els.pauseBtn.addEventListener('click', togglePause);
els.stepBtn.addEventListener('click', stepExec);
els.resetBtn.addEventListener('click', () => hardReset(false));
}
// --- 视图与布局 ---
function toggleLayout() {
const isDefault = els.mainContent.classList.contains('layout-default');
if (isDefault) {
els.mainContent.classList.remove('layout-default');
els.mainContent.classList.add('layout-sidebar');
els.layoutToggle.innerHTML = '<i class="fas fa-arrow-up text-indigo-500"></i> 默认视图';
} else {
els.mainContent.classList.remove('layout-sidebar');
els.mainContent.classList.add('layout-default');
els.layoutToggle.innerHTML = '<i class="fas fa-columns text-indigo-500"></i> 侧边视图';
}
setTimeout(recalculatePositions, 300);
}
function setupResizeObserver() {
new ResizeObserver(() => {
if (state.visualItems.length > 0) requestAnimationFrame(recalculatePositions);
}).observe(els.stage);
}
function recalculatePositions() {
state.visualItems.forEach(item => {
const coords = getCoordinates(item.currentIdx, item.depth);
item.el.style.left = `${coords.left}px`;
item.el.style.top = `${coords.top}px`;
});
// 重新定位指针
if (state.currentPointers.l && state.currentPointers.r) {
showPointers(state.currentPointers.l, state.currentPointers.r, false);
}
}
function getCoordinates(index, depth) {
const totalItems = state.visualItems.length;
const stageWidth = els.stage.clientWidth || 800;
const contentWidth = totalItems * (config.blockSize + config.gapX) - config.gapX;
// 居中计算
const startX = Math.max(20, (stageWidth - contentWidth) / 2);
return {
left: startX + index * (config.blockSize + config.gapX),
top: config.baseTop + depth * config.levelHeight
};
}
// --- 数据生成与渲染 ---
function generateArray(isNew = true) {
if (isNew) {
const arr = Array.from({length: state.arraySize}, () => Math.floor(Math.random() * 90) + 10);
state.savedInitialData = [...arr];
createVisualItems(arr);
} else {
createVisualItems(state.savedInitialData);
}
resetState();
}
function createVisualItems(arr) {
// 清理
const items = els.stage.querySelectorAll('.array-item');
items.forEach(el => el.remove());
els.pointerLayer.innerHTML = '';
state.visualItems = [];
state.currentPointers = { l: null, r: null };
arr.forEach((val, idx) => {
const el = document.createElement('div');
el.className = 'array-item color-default';
el.textContent = val;
els.stage.appendChild(el);
state.visualItems.push({
id: idx,
value: val,
el: el,
currentIdx: idx,
depth: 0
});
});
recalculatePositions();
}
function resetState() {
state.isSorting = false;
state.isPaused = false;
state.isComplete = false;
state.stopFlag = false;
state.stepResolver = null;
state.comparisons = 0;
els.compCount.textContent = '0';
updateStatus('准备就绪', 'idle');
els.log.innerHTML = '<div class="text-slate-500 flex items-start gap-2"><span class="text-indigo-400 font-bold">></span><span>系统重置就绪</span></div>';
els.startBtn.disabled = false;
els.startBtn.innerHTML = '<i class="fas fa-play"></i> 开始归并';
els.pauseBtn.disabled = true;
els.stepBtn.disabled = true;
els.pointerLayer.innerHTML = '';
}
// --- 核心逻辑 ---
async function startSort() {
if (state.isSorting) return;
if (state.isComplete) generateArray(false);
state.isSorting = true;
state.stopFlag = false;
updateStatus('归并中', 'running');
els.startBtn.disabled = true;
els.pauseBtn.disabled = false;
els.stepBtn.disabled = false;
els.resetBtn.disabled = false;
log('🚀 归并排序开始');
try {
await mergeSort(0, state.visualItems.length - 1, 1);
finishSort();
} catch (e) {
if (e.message !== 'ABORT') console.error(e);
updateStatus('已停止', 'paused');
}
}
async function mergeSort(l, r, depth) {
if (l >= r || state.stopFlag) return;
const m = Math.floor((l + r) / 2);
// 拆分过程:下沉
log(`🔽 拆分区间 [${l}, ${r}] 到深度 ${depth}`);
for (let i = l; i <= r; i++) {
moveItem(state.visualItems[i], i, depth);
}
// 染色表示左右分支
setRangeColor(l, m, 'color-left');
setRangeColor(m + 1, r, 'color-right');
await waitStep();
await mergeSort(l, m, depth + 1);
await mergeSort(m + 1, r, depth + 1);
// 合并过程
await merge(l, m, r, depth - 1);
}
async function merge(l, m, r, targetDepth) {
if (state.stopFlag) throw new Error('ABORT');
log(`🔄 合并区间: [${l}-${m}] 和 [${m+1}-${r}]`);
const temp = [];
let i = l, j = m + 1;
// 创建快照以便在动画移动时引用正确的对象
const currentSnapshot = [...state.visualItems];
while (i <= m && j <= r) {
if (state.stopFlag) throw new Error('ABORT');
state.comparisons++;
els.compCount.textContent = state.comparisons;
const itemL = currentSnapshot[i];
const itemR = currentSnapshot[j];
// 显示指针和高亮
showPointers(itemL, itemR);
itemL.el.classList.add('color-comparing');
itemR.el.classList.add('color-comparing');
await waitStep();
let winner;
if (itemL.value <= itemR.value) {
log(` 👈 左边小: ${itemL.value} <= ${itemR.value}`);
winner = itemL;
i++;
} else {
log(` 👉 右边小: ${itemR.value} < ${itemL.value}`);
winner = itemR;
j++;
}
// 移除高亮,设置为有序色
itemL.el.classList.remove('color-comparing');
itemR.el.classList.remove('color-comparing');
winner.el.className = 'array-item color-sorted';
// 移动到上一层的新位置
const targetIdx = l + temp.length;
moveItem(winner, targetIdx, targetDepth);
temp.push(winner);
await waitStep(0.6); // 稍微快一点移动
}
// 处理剩余元素
const processRemaining = async (idx) => {
if(state.stopFlag) throw new Error('ABORT');
const item = currentSnapshot[idx];
item.el.className = 'array-item color-sorted';
moveItem(item, l + temp.length, targetDepth);
temp.push(item);
await waitStep(0.3);
};
while (i <= m) await processRemaining(i++);
while (j <= r) await processRemaining(j++);
removePointers();
// 更新主数组状态,确保后续逻辑引用的索引正确
for(let k=0; k<temp.length; k++) {
state.visualItems[l + k] = temp[k];
}
// 恢复该层级颜色(如果不是最顶层)
if (targetDepth > 0) {
// 可选:稍微停留展示合并结果
await waitStep(0.5);
}
}
// --- 辅助功能 ---
function moveItem(item, targetIndex, targetDepth) {
const coords = getCoordinates(targetIndex, targetDepth);
item.el.style.left = `${coords.left}px`;
item.el.style.top = `${coords.top}px`;
item.currentIdx = targetIndex;
item.depth = targetDepth;
if(targetDepth > 0) item.el.parentElement.classList.add('item-deep');
else item.el.parentElement.classList.remove('item-deep');
}
function setRangeColor(start, end, className) {
for(let i = start; i <= end; i++) {
if(state.visualItems[i]) {
// 清除之前的颜色类,保留基础类
state.visualItems[i].el.className = `array-item ${className}`;
}
}
}
// 指针管理
function showPointers(itemL, itemR) {
state.currentPointers = { l: itemL, r: itemR };
els.pointerLayer.innerHTML = '';
const createPtr = (type, item) => {
const ptr = document.createElement('div');
ptr.className = `pointer pointer-${type}`;
ptr.innerHTML = `<div class="pointer-arrow"></div><div class="pointer-tag">${type.toUpperCase()}</div>`;
const coords = getCoordinates(item.currentIdx, item.depth);
// 指针显示在方块下方
ptr.style.left = `${coords.left + config.blockSize/2 - 20}px`;
ptr.style.top = `${coords.top + config.blockSize + 5}px`;
return ptr;
};
els.pointerLayer.appendChild(createPtr('l', itemL));
els.pointerLayer.appendChild(createPtr('r', itemR));
}
function removePointers() {
els.pointerLayer.innerHTML = '';
state.currentPointers = { l: null, r: null };
}
// 流程控制
async function waitStep(ratio = 1) {
if (state.stopFlag) throw new Error('ABORT');
if (state.isPaused) {
return new Promise(resolve => { state.stepResolver = resolve; });
}
return new Promise(resolve => setTimeout(resolve, state.speed * ratio));
}
function togglePause() {
if (!state.isSorting) return;
state.isPaused = !state.isPaused;
if (state.isPaused) {
els.pauseBtn.innerHTML = '<i class="fas fa-play"></i> 继续';
updateStatus('已暂停', 'paused');
log('⏸️ 流程暂停');
} else {
els.pauseBtn.innerHTML = '<i class="fas fa-pause"></i> 暂停';
updateStatus('归并中', 'running');
log('▶️ 流程继续');
if (state.stepResolver) {
state.stepResolver();
state.stepResolver = null;
}
}
}
function stepExec() {
if (!state.isSorting) {
state.isPaused = true;
startSort();
updateStatus('单步模式', 'paused');
els.pauseBtn.innerHTML = '<i class="fas fa-play"></i> 继续';
} else if (state.isPaused && state.stepResolver) {
state.stepResolver();
state.stepResolver = null;
}
}
function hardReset(newArray = false) {
state.stopFlag = true;
if (state.stepResolver) state.stepResolver();
setTimeout(() => {
generateArray(newArray);
}, 100);
}
function finishSort() {
state.isSorting = false;
state.isComplete = true;
updateStatus('已完成', 'running');
removePointers();
// 最终动画
state.visualItems.forEach(item => {
item.el.className = 'array-item color-sorted';
item.el.style.transform = 'scale(1.1)';
setTimeout(() => item.el.style.transform = 'scale(1)', 300);
});
els.startBtn.disabled = false;
els.startBtn.innerHTML = '<i class="fas fa-redo"></i> 重新开始';
els.pauseBtn.disabled = true;
els.stepBtn.disabled = true;
log(`🏆 排序完成!共比较 ${state.comparisons} 次`);
}
// 工具函数
function updateStatus(text, type) {
els.statusText.textContent = text;
els.statusDot.className = `status-dot dot-${type}`;
}
function log(msg) {
const div = document.createElement('div');
div.className = 'log-entry text-slate-600 flex items-start gap-2 border-l-2 border-indigo-100 pl-2 py-1';
const time = new Date().toLocaleTimeString('zh-CN', { hour12: false });
div.innerHTML = `<span class="text-xs text-indigo-400 font-mono mt-0.5">[${time}]</span> <span class="flex-1">${msg}</span>`;
els.log.appendChild(div);
els.log.scrollTop = els.log.scrollHeight;
}
function clearLog() {
els.log.innerHTML = '';
}
</script>
</body>
</html>