-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbubble(2).html
More file actions
808 lines (712 loc) · 36.9 KB
/
Copy pathbubble(2).html
File metadata and controls
808 lines (712 loc) · 36.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
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>冒泡排序可视化 | Bubble 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: #3b82f6;
--secondary: #8b5cf6;
--bg-gradient: linear-gradient(135deg, #f0f9ff 0%, #e0e7ff 100%);
}
body {
font-family: 'Inter', sans-serif;
background: var(--bg-gradient);
color: #334155;
min-height: 100vh;
}
/* 玻璃拟态效果 */
.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;
}
/* 柱子容器 */
.array-container {
position: relative;
height: 280px;
width: 100%;
display: flex; /* 用于色块模式居中 */
align-items: flex-end; /* 默认底部对齐 */
}
/* 通用元素样式 (柱子或色块) */
.array-item {
position: absolute;
transition: height 0.3s ease, background-color 0.3s ease, left 0.4s cubic-bezier(0.4, 0, 0.2, 1), transform 0.3s ease;
border-radius: 6px 6px 2px 2px;
background-color: #60a5fa; /* Blue 400 */
display: flex;
align-items: center;
justify-content: center;
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
}
/* 柱状模式特定样式 */
.mode-bar .array-item {
bottom: 0;
align-items: flex-end;
padding-bottom: 4px;
}
/* 色块模式特定样式 */
.mode-block .array-item {
bottom: 50%; /* 垂直居中 */
transform: translateY(50%);
border-radius: 8px;
font-size: 14px;
font-weight: bold;
color: white;
}
/* 状态颜色 */
.color-default { background-color: #60a5fa; }
.color-comparing {
background-color: #f59e0b !important; /* Amber 500 */
box-shadow: 0 0 15px rgba(245, 158, 11, 0.4);
z-index: 10;
}
.color-swapping {
background-color: #ef4444 !important; /* Red 500 */
transform: translateY(-10px) scale(1.05) !important; /* 交换时跳起 */
z-index: 20;
}
/* 色块模式下不需要跳起太高,因为是居中的 */
.mode-block .color-swapping {
transform: translateY(calc(50% - 10px)) scale(1.1) !important;
}
.color-sorted { background-color: #10b981 !important; } /* Emerald 500 */
/* 指针指示器 */
.pointer-container {
position: absolute;
bottom: -35px;
width: 100%;
height: 30px;
pointer-events: none;
}
/* 适配色块模式的指针位置 */
.mode-block ~ .pointer-container {
bottom: 15%;
}
.pointer {
position: absolute;
transition: left 0.4s cubic-bezier(0.4, 0, 0.2, 1);
display: flex;
flex-direction: column;
align-items: center;
z-index: 20;
bottom: 0;
}
.pointer-tag {
font-size: 10px;
font-weight: 800;
padding: 2px 6px;
border-radius: 4px;
color: white;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
margin-bottom: 2px;
}
.pointer-arrow {
width: 0; height: 0;
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-bottom: 6px solid;
}
.pointer-j .pointer-tag { background-color: #f59e0b; }
.pointer-j .pointer-arrow { border-bottom-color: #f59e0b; }
.pointer-next .pointer-tag { background-color: #8b5cf6; }
.pointer-next .pointer-arrow { border-bottom-color: #8b5cf6; }
/* 代码高亮区 */
.code-block {
font-family: 'JetBrains Mono', monospace;
font-size: 0.8rem;
background: #1e293b;
color: #94a3b8;
border-radius: 0.5rem;
padding: 1rem;
line-height: 1.6;
}
.code-line {
padding: 0 4px;
border-radius: 2px;
transition: all 0.2s;
display: block;
}
.code-active {
background: rgba(59, 130, 246, 0.3);
color: #ffffff;
border-left: 2px solid #3b82f6;
margin-left: -2px;
}
/* 终端日志样式 */
.log-container {
font-family: 'JetBrains Mono', monospace;
background: #f8fafc;
border: 1px solid #e2e8f0;
border-left: 4px solid #3b82f6;
}
.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); } }
</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-blue-600 rounded-xl text-white shadow-lg shadow-blue-200">
<i class="fas fa-soap fa-lg"></i>
</div>
<h1 class="text-3xl font-extrabold text-slate-800 tracking-tight">冒泡排序</h1>
</div>
<p class="text-slate-500 font-medium">Bubble Sort Visualization Hub</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-blue-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-5 gap-6 items-end">
<!-- Visualization Mode -->
<div>
<label class="text-xs font-bold text-slate-500 uppercase block mb-2">视图模式</label>
<select id="viewMode" 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-blue-500 transition shadow-sm font-medium text-slate-700">
<option value="bar">📊 高度柱状图</option>
<option value="block">🧊 等高色块图</option>
</select>
</div>
<!-- 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-blue-600 font-bold font-mono text-sm">12</span>
</div>
<input type="range" id="sizeSlider" min="5" max="25" value="12" class="w-full accent-blue-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-blue-600 font-bold font-mono text-sm">5</span>
</div>
<input type="range" id="speedSlider" min="1" max="10" value="5" class="w-full accent-blue-600 cursor-pointer h-2 bg-slate-200 rounded-lg appearance-none">
</div>
<!-- Custom Input -->
<div>
<label class="text-xs font-bold text-slate-500 uppercase block mb-2">自定义数据</label>
<input type="text" id="customArray" placeholder="例如: 45, 12, 8" 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-blue-500 transition shadow-sm font-mono">
</div>
<!-- Generate Button -->
<button id="generateBtn" class="bg-blue-50 text-blue-600 h-10 px-4 rounded-xl font-bold hover:bg-blue-100 transition border border-blue-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-8 pb-4 border-b border-slate-100 flex-wrap gap-4">
<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>
<!-- Metrics -->
<div class="flex items-center gap-3">
<div class="text-sm bg-slate-50 px-3 py-1.5 rounded-lg border border-slate-100 flex items-center gap-2">
<i class="fas fa-stopwatch text-blue-400"></i>
<span class="text-slate-500 font-semibold">耗时:</span>
<span id="timerDisplay" class="font-mono font-bold text-slate-700">0.0s</span>
</div>
<div class="text-sm bg-slate-50 px-3 py-1.5 rounded-lg border border-slate-100 flex items-center gap-2">
<i class="fas fa-exchange-alt text-green-400"></i>
<span class="text-slate-500 font-semibold">交换:</span>
<span id="swapCount" class="font-mono font-bold text-slate-700">0</span>
</div>
</div>
</div>
<!-- Visualization Container -->
<div class="visualization-container relative mb-8" style="height: 300px;">
<div id="sortArray" class="array-container mode-bar">
<!-- Bars/Blocks will be injected here -->
</div>
<!-- Pointers -->
<div id="pointerContainer" class="pointer-container">
<div id="pointerJ" class="pointer pointer-j" style="display:none;">
<div class="pointer-arrow"></div>
<div class="pointer-tag">j</div>
</div>
<div id="pointerNext" class="pointer pointer-next" style="display:none;">
<div class="pointer-arrow"></div>
<div class="pointer-tag">j+1</div>
</div>
</div>
</div>
<!-- Controls -->
<div class="flex flex-wrap justify-center gap-3">
<button id="startBtn" class="px-6 py-2.5 bg-blue-600 text-white rounded-xl font-bold hover:bg-blue-700 transition shadow-lg shadow-blue-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-slate-700 rounded-xl font-bold hover:bg-slate-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-blue-500"></i> 执行日志
</div>
</div>
<div id="logContent" 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-blue-400 font-bold">></span>
<span>等待系统指令...</span>
</div>
</div>
</section>
</div>
<!-- Right/Bottom Section: Algorithm Info & Code -->
<aside id="infoSection" class="glass-card rounded-2xl p-6 border-t-4 border-blue-500 h-full flex flex-col gap-6">
<!-- Code Trace (Replaces Floating Modal) -->
<div>
<h3 class="text-sm font-bold text-slate-800 mb-3 flex items-center gap-2">
<i class="fas fa-code text-purple-500"></i> 代码跟踪
</h3>
<div class="code-block shadow-inner" id="codeBox">
<span class="code-line" id="line-0">procedure bubbleSort(A):</span>
<span class="code-line" id="line-1"> n = length(A)</span>
<span class="code-line" id="line-2"> for i from 0 to n-1:</span>
<span class="code-line" id="line-3"> for j from 0 to n-i-2:</span>
<span class="code-line" id="line-4"> if A[j] > A[j+1]:</span>
<span class="code-line" id="line-5"> swap(A[j], A[j+1])</span>
<span class="code-line" id="line-6"> // A[n-1-i] is sorted</span>
</div>
</div>
<!-- Legend -->
<div class="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-2 text-xs font-medium text-slate-600">
<div class="flex items-center gap-2"><div class="w-3 h-3 rounded bg-amber-500"></div>正在比较</div>
<div class="flex items-center gap-2"><div class="w-3 h-3 rounded bg-red-500"></div>正在交换</div>
<div class="flex items-center gap-2"><div class="w-3 h-3 rounded bg-emerald-500"></div>已排序</div>
<div class="flex items-center gap-2"><div class="w-3 h-3 rounded bg-blue-400"></div>待排序</div>
</div>
</div>
<!-- Algorithm Details -->
<div class="text-slate-600 text-sm">
<h4 class="font-bold text-slate-800 mb-2">💡 核心思想</h4>
<p class="leading-relaxed mb-4">通过重复地走访要排序的数列,一次比较两个元素,如果他们的顺序错误就把他们交换过来。</p>
<div class="flex flex-wrap gap-2 mb-2">
<span class="px-2 py-1 bg-blue-100 text-blue-700 rounded text-xs font-bold">时间: O(n²)</span>
<span class="px-2 py-1 bg-green-100 text-green-700 rounded text-xs font-bold">空间: O(1)</span>
<span class="px-2 py-1 bg-purple-100 text-purple-700 rounded text-xs font-bold">稳定</span>
</div>
</div>
</aside>
</div>
</div>
<!-- Footer -->
<footer class="mt-8 text-center text-slate-400 text-xs pb-4">
<p>Bubble Sort Pro Visualization</p>
</footer>
</div>
<script>
// --- 全局变量与状态 ---
let array = [];
let doms = [];
let originalArray = [];
let state = {
isSorting: false,
isPaused: false,
stepMode: false,
stepResolver: null,
stopFlag: false,
swaps: 0,
startTime: 0,
timerInterval: null
};
let speed = 500;
let vizMode = 'bar'; // 'bar' or 'block'
// --- DOM 元素引用 ---
const els = {
sizeSlider: document.getElementById('sizeSlider'),
sizeValue: document.getElementById('sizeValue'),
speedSlider: document.getElementById('speedSlider'),
speedValue: document.getElementById('speedValue'),
customArray: document.getElementById('customArray'),
viewMode: document.getElementById('viewMode'),
generateBtn: document.getElementById('generateBtn'),
startBtn: document.getElementById('startBtn'),
pauseBtn: document.getElementById('pauseBtn'),
stepBtn: document.getElementById('stepBtn'),
resetBtn: document.getElementById('resetBtn'),
sortArray: document.getElementById('sortArray'),
logContent: document.getElementById('logContent'),
statusIndicator: document.getElementById('statusIndicator'),
statusText: document.getElementById('statusText'),
timerDisplay: document.getElementById('timerDisplay'),
swapCount: document.getElementById('swapCount'),
pointerJ: document.getElementById('pointerJ'),
pointerNext: document.getElementById('pointerNext'),
layoutToggle: document.getElementById('layoutToggle'),
mainContent: document.getElementById('mainContent')
};
// --- 初始化 ---
document.addEventListener('DOMContentLoaded', () => {
updateSizeValue();
updateSpeedValue();
generateNewArray();
// 布局切换
els.layoutToggle.addEventListener('click', toggleLayout);
// 输入事件
els.sizeSlider.addEventListener('input', () => {
updateSizeValue();
generateNewArray();
});
els.speedSlider.addEventListener('input', updateSpeedValue);
els.viewMode.addEventListener('change', (e) => {
vizMode = e.target.value;
els.sortArray.className = `array-container mode-${vizMode}`;
renderArray();
// 如果在排序中切换模式,重置指针显示
if(state.isSorting) {
els.pointerJ.style.display = 'none';
els.pointerNext.style.display = 'none';
}
});
els.generateBtn.addEventListener('click', () => {
const custom = els.customArray.value.trim();
if (custom) {
try {
const parsed = custom.split(/[,, ]+/).map(Number).filter(n => !isNaN(n));
if (parsed.length < 2) throw new Error();
if (parsed.length > 30) { alert('数量过多,建议30以内'); return; }
array = parsed;
originalArray = [...array];
resetState();
renderArray();
} catch {
alert('请输入有效的数字数组,例如: 45, 12, 8');
}
} else {
generateNewArray();
}
});
// 控制按钮
els.startBtn.addEventListener('click', startSort);
els.pauseBtn.addEventListener('click', togglePause);
els.stepBtn.addEventListener('click', stepSort);
els.resetBtn.addEventListener('click', () => {
state.stopFlag = true;
if (state.stepResolver) state.stepResolver();
setTimeout(() => {
array = [...originalArray];
resetState();
renderArray();
}, 100);
});
// 窗口调整
window.addEventListener('resize', () => {
if (array.length > 0) renderArray();
});
});
// --- 核心功能函数 ---
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-blue-500"></i> 默认视图';
} else {
els.mainContent.classList.remove('layout-sidebar');
els.mainContent.classList.add('layout-default');
els.layoutToggle.innerHTML = '<i class="fas fa-columns text-blue-500"></i> 侧边视图';
}
setTimeout(renderArray, 300);
}
function updateSizeValue() { els.sizeValue.textContent = els.sizeSlider.value; }
function updateSpeedValue() {
els.speedValue.textContent = els.speedSlider.value;
// 速度映射:值越大(10),延迟越小(50ms);值越小(1),延迟越大(1000ms)
speed = 1000 - (els.speedSlider.value - 1) * 100;
if(speed < 50) speed = 50;
}
function generateNewArray() {
const size = parseInt(els.sizeSlider.value);
array = [];
for (let i = 0; i < size; i++) {
array.push(Math.floor(Math.random() * 90) + 10);
}
originalArray = [...array];
resetState();
renderArray();
}
function resetState() {
state = {
isSorting: false,
isPaused: false,
stepMode: false,
stepResolver: null,
stopFlag: false,
swaps: 0,
startTime: 0,
timerInterval: null
};
clearInterval(state.timerInterval);
updateStatus('未开始', 'idle');
els.timerDisplay.textContent = '0.0s';
els.swapCount.textContent = '0';
els.pointerJ.style.display = 'none';
els.pointerNext.style.display = 'none';
els.logContent.innerHTML = '<div class="text-slate-500 flex items-start gap-2"><span class="text-blue-400 font-bold">></span><span>系统重置就绪</span></div>';
highlightCode(-1);
els.startBtn.disabled = false;
els.startBtn.innerHTML = '<i class="fas fa-play"></i> 开始排序';
els.pauseBtn.innerHTML = '<i class="fas fa-pause"></i> 暂停';
els.pauseBtn.disabled = true;
els.stepBtn.disabled = true;
}
function updateStatus(text, type) {
els.statusText.textContent = text;
els.statusIndicator.className = `status-dot dot-${type}`;
}
// 渲染可视化数组
function renderArray() {
els.sortArray.innerHTML = '';
doms = [];
const maxValue = Math.max(...array, 100);
const containerWidth = els.sortArray.clientWidth;
// 计算宽度与间隙
const totalGap = (array.length + 1) * 4;
const availableWidth = containerWidth - totalGap;
const itemWidth = Math.max(12, Math.floor(availableWidth / array.length));
// 重新计算实际间隙以均匀分布
const realGap = (containerWidth - itemWidth * array.length) / (array.length + 1);
array.forEach((value, index) => {
const item = document.createElement('div');
item.className = 'array-item color-default';
// 设置位置
item.style.left = `${realGap + index * (itemWidth + realGap)}px`;
item.style.width = `${itemWidth}px`;
// 根据模式设置样式
if (vizMode === 'bar') {
const heightPercent = (value / maxValue) * 90;
item.style.height = `${heightPercent}%`;
if (itemWidth > 24) {
item.innerHTML = `<span class="mb-1 text-xs text-white font-bold opacity-90">${value}</span>`;
}
} else {
// Block Mode
item.style.height = `${itemWidth}px`; // 正方形
item.innerHTML = `<span>${value}</span>`;
}
els.sortArray.appendChild(item);
doms.push(item);
});
}
function trackPointer(pointer, index) {
if (index < 0 || index >= doms.length) {
pointer.style.display = 'none';
return;
}
pointer.style.display = 'flex';
const item = doms[index];
const left = parseFloat(item.style.left);
const width = parseFloat(item.style.width);
// 居中对齐
const pWidth = 30; // 宽一点适配 j+1
pointer.style.left = `${left + width/2 - pWidth/2}px`;
}
function highlightCode(lineIndex) {
document.querySelectorAll('.code-line').forEach(el => el.classList.remove('code-active'));
if (lineIndex >= 0) {
const line = document.getElementById(`line-${lineIndex}`);
if (line) line.classList.add('code-active');
}
}
// --- 排序逻辑 ---
async function wait() {
if (state.stopFlag) throw new Error('ABORT');
if (state.stepMode) {
return new Promise(resolve => { state.stepResolver = resolve; });
}
return new Promise(resolve => setTimeout(resolve, speed));
}
async function startSort() {
if (state.isSorting) return;
state.isSorting = true;
state.stopFlag = false;
updateStatus('排序中', 'running');
els.startBtn.disabled = true;
els.pauseBtn.disabled = false;
els.stepBtn.disabled = false;
state.startTime = Date.now();
state.timerInterval = setInterval(() => {
if(!state.isPaused && !state.stopFlag) {
const diff = (Date.now() - state.startTime) / 1000;
els.timerDisplay.textContent = diff.toFixed(1) + 's';
} else {
// 暂停时调整 startTime 以避免跳秒
state.startTime = Date.now() - (parseFloat(els.timerDisplay.textContent) * 1000);
}
}, 100);
try {
log('🚀 冒泡排序开始');
highlightCode(0);
await bubbleSort();
completeSort();
} catch (e) {
if (e.message !== 'ABORT') console.error(e);
updateStatus('已停止', 'paused');
}
}
async function bubbleSort() {
const n = array.length;
highlightCode(1);
highlightCode(2);
for (let i = 0; i < n; i++) {
let swapped = false;
log(`🔄 第 ${i+1} 轮扫描开始`);
for (let j = 0; j < n - i - 1; j++) {
if (state.stopFlag) throw new Error('ABORT');
// 1. 比较
highlightCode(3);
trackPointer(els.pointerJ, j);
trackPointer(els.pointerNext, j + 1);
doms[j].classList.add('color-comparing');
doms[j+1].classList.add('color-comparing');
highlightCode(4);
log(`🔍 比较 [${j}]:${array[j]} 和 [${j+1}]:${array[j+1]}`);
await wait();
// 2. 交换
if (array[j] > array[j+1]) {
log(`⚡ 交换 ${array[j]} > ${array[j+1]}`);
highlightCode(5);
// 视觉样式
doms[j].classList.add('color-swapping');
doms[j+1].classList.add('color-swapping');
await wait(); // 展示“准备交换”状态
// 执行位置交换动画
const leftJ = doms[j].style.left;
const leftNext = doms[j+1].style.left;
doms[j].style.left = leftNext;
doms[j+1].style.left = leftJ;
// 数据交换
[doms[j], doms[j+1]] = [doms[j+1], doms[j]];
[array[j], array[j+1]] = [array[j+1], array[j]];
state.swaps++;
els.swapCount.textContent = state.swaps;
swapped = true;
// 更新指针
trackPointer(els.pointerJ, j); // 注意:doms已换,但指针逻辑位置j还是j
trackPointer(els.pointerNext, j+1);
await wait(); // 等待交换动画完成
doms[j].classList.remove('color-swapping');
doms[j+1].classList.remove('color-swapping');
}
// 清理比较样式
doms[j].classList.remove('color-comparing');
doms[j+1].classList.remove('color-comparing');
}
// 标记已排序
doms[n - 1 - i].classList.add('color-sorted');
log(`✅ 元素 ${array[n - 1 - i]} 已归位`);
highlightCode(6);
await wait();
// 优化:如果没有交换,说明已经有序(虽然标准演示通常跑完)
/* if (!swapped) break; */
}
// 确保第一个元素也标记为 sorted
if(doms[0]) doms[0].classList.add('color-sorted');
}
function togglePause() {
if (!state.isSorting) return;
state.isPaused = !state.isPaused;
state.stepMode = 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 stepSort() {
if (!state.isSorting) {
startSort();
state.stepMode = true;
state.isPaused = true;
els.pauseBtn.innerHTML = '<i class="fas fa-play"></i> 继续';
updateStatus('单步模式', 'paused');
} else if (state.stepMode && state.stepResolver) {
state.stepResolver();
state.stepResolver = null;
}
}
function completeSort() {
state.isSorting = false;
clearInterval(state.timerInterval);
updateStatus('已完成', 'running');
els.pointerJ.style.display = 'none';
els.pointerNext.style.display = 'none';
highlightCode(-1);
// 庆祝动画
doms.forEach((item, idx) => {
setTimeout(() => {
item.style.transform = vizMode === 'bar' ? 'translateY(-10px)' : 'translateY(calc(50% - 10px))';
setTimeout(() => {
item.style.transform = vizMode === 'bar' ? 'translateY(0)' : 'translateY(50%)';
}, 200);
}, idx * 30);
});
els.startBtn.disabled = false;
els.startBtn.innerHTML = '<i class="fas fa-redo"></i> 重新开始';
els.pauseBtn.disabled = true;
els.stepBtn.disabled = true;
log('🏆 排序完成!');
}
function log(msg) {
const div = document.createElement('div');
div.className = 'log-entry text-slate-600 flex items-start gap-2 border-l-2 border-blue-100 pl-2 py-1';
const time = new Date().toLocaleTimeString('zh-CN', { hour12: false });
div.innerHTML = `<span class="text-xs text-blue-400 font-mono mt-0.5">[${time}]</span> <span class="flex-1">${msg}</span>`;
els.logContent.appendChild(div);
els.logContent.scrollTop = els.logContent.scrollHeight;
}
</script>
</body>
</html>