-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmergeSort.html
723 lines (615 loc) · 25.1 KB
/
mergeSort.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Merge Sort</title>
<meta name="description" content="Merge sort visualized step by step with its time and space complexities" />
<meta name="keywords"
content="merge sort, merge sort visualized,step by step, merge sort in easy way, time complexity, space complexity, merge sort properties, arun neupane,sorting" />
<link rel="icon" href="./images/sort.png" type="image/x-icon">
<link rel="stylesheet" href="./styles.css">
<link rel="manifest" href="./manifest.json">
<!-- For ios -->
<link rel="apple-touch-icon" href="./images/sort.png">
<meta name="apple-mobile-web-app-status-bar" content="1338BE">
<style>
.numbers-wrapper {
display: flex;
border: 5px solid green;
}
</style>
<link href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism-tomorrow.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/prism.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-clike.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-c.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-cpp.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-python.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-java.min.js"></script>
</head>
<body>
<nav>
<div class="menu-toggle" onclick="toggleMenu()">
<span></span>
<span></span>
<span></span>
</div>
<div class="nav-links">
<a href="./index.html">Home</a>
<a href="./bubbleSort.html">Bubble <span class="sort-text">sort</span></a>
<a href="./selectionSort.html">Selection <span class="sort-text">sort</span></a>
<a href="./insertionSort.html">Insertion <span class="sort-text">sort</span></a>
<a href="./mergeSort.html" class="bb">Merge <span class="sort-text">sort</span></a>
<a href="./quickSort.html">Quick <span class="sort-text">sort</span></a>
<a href="./heapSort.html">Heap <span class="sort-text">sort</span></a>
<a href="./radixSort.html">Radix <span class="sort-text">sort</span></a>
<a href="./shellSort.html">Shell <span class="sort-text">sort</span></a>
<a href="./summary.html">Summary</a>
<a id="install-button-mobile">Install</a>
</div>
</nav>
<div class="cursor big"></div>
<div class="cursor small"></div>
<div id="context-menu" class="hidden">
<ul>
<li onclick="window.location.reload(true);">Refresh</li>
<li onclick="window.open('./contact.html','_self')">
Contact
</li>
<li>
Share
<ul class="submenu">
<li class="submenu-item">
<a href="https://www.facebook.com/sharer/sharer.php?u=https://easysorting.netlify.app"e=Hey%20check%20out%20this%20sorting%20algorithm%20visualizer"
target="_blank" rel="noopener">
<img src="./images/svg-icons/facebook.svg" alt="Facebook" class="icon">
</a>
</li>
<li class="submenu-item">
<a href="https://www.instagram.com" target="_blank" rel="noopener">
<img src="./images/svg-icons/instagram.svg" alt="Instagram" class="icon">
</a>
</li>
<li class="submenu-item">
<a href="https://wa.me/?text=Hey%20check%20out%20this%20sorting%20algorithm%20visualizer%20-%20https://easysorting.netlify.app"
target="_blank" rel="noopener">
<img src="./images/svg-icons/whatsapp.svg" alt="Whatsapp" class="icon">
</a>
</li>
<li class="submenu-item">
<a href="https://t.me/share/url?url=https://easysorting.netlify.app&text=Hey%20check%20out%20this%20sorting%20algorithm%20visualizer"
target="_blank" rel="noopener">
<img src="./images/svg-icons/telegram.svg" alt="Telegram" class="icon">
</a>
</li>
</ul>
</li>
<li>
Follow me
<ul class="submenu">
<li class="submenu-item">
<a href="https://www.facebook.com/arunneupane9000/" target="_blank" rel="noopener">
<img src="./images/svg-icons/facebook.svg" alt="Facebook" class="icon">
</a>
</li>
<li class="submenu-item">
<a href="https://www.instagram.com/arundada9000" target="_blank" rel="noopener">
<img src="./images/svg-icons/instagram.svg" alt="Instagram" class="icon">
</a>
</li>
<li class="submenu-item">
<a href="https://www.github.com/arundada9000" target="_blank" rel="noopener">
<img src="./images/svg-icons/github.svg" alt="Telegram" class="icon">
</a>
</li>
<li class="submenu-item">
<a href="https://www.youtube.com/@code_with_ease" target="_blank" rel="noopener">
<img src="./images/svg-icons/youtube.svg" alt="Youtube" class="icon">
</a>
</li>
</ul>
</li>
<li onclick="window.open('./feedback.html','_self')">
Feedback
</li>
<li id="installButton">Install</li>
</ul>
</div>
<div class="progress-bar-container">
<div class="progress-bar"></div>
</div>
<div class="container">
<section class="front">
<div class="front-main">
<div class="icon-container">
<img src="./images/merge.webp" alt="merge sort">
<h1>Merge Sort</h1>
</div>
<div class="sort-input">
<input type="text" id="input-num" label="Enter numbers" title="Enter numbers separated with commas"
placeholder="Enter numbers separated with commas as 16,15,15,10,1">
<div class="buttons-div">
<div class="sort-btn" id="generate-random-btn" title="Generate random numbers button"
onclick="randomGenerate();">
<img src="./images/magic.png" alt="Generate Random Numbers" title="Generate random numbers">
</div>
<button id="sort-btn" class="sort-btn">Sort</button>
</div>
</div>
</div>
<div class="buttons-div"><button id="fast-btn" class="control-btn">Fast Visualization</button>
<button id="skip" class="control-btn">Skip Visualization</button>
</div>
<div class="passesandinfo">
<div class="numbers" id="num-div"></div>
<div class="passes" id="passes"></div>
</div>
</section>
<div class="howto-wrapper scroll-animate">
<div class="howto" id="howto">
<div class="qs">
<h3>How to use ?</h3>
<button class="show">+</button>
<button class="hide">-</button>
</div>
<div class="ans">
<p>
Enter an array separated by commas as : 16,15,15,10,1 or just press the hand icon to generate a
random array then press enter or Sort button. Sorting
will
start
and
you can watch each pass as it gets sorted.
When it shows green it means the two of them are
being
compared
when red shows, it means the left number is greater than right number so it needs swapping
The blue color means the number is
at its
correct position and thus sorted
it will continue to check other numbers until it reaches end.
</p>
</div>
</div>
</div>
<div class="sorting-algorithm-container">
<h1 class="algorithm-title scroll-animate">Merge Sort Overview</h1>
<section class="history scroll-animate">
<h2 class="section-title">History</h2>
<p>Merge sort was invented by John von Neumann in 1945. It is a classic divide-and-conquer algorithm
that is particularly effective for large datasets and is widely used in computer science and
programming.</p>
</section>
<section class="current-uses scroll-animate">
<h2 class="section-title">Current Uses</h2>
<ul>
<li><strong>Large Data Sets:</strong> Often employed for sorting large datasets where performance is
critical.</li>
<li><strong>Stable Sort:</strong> Utilized in applications where stable sorting is required.</li>
<li><strong>External Sorting:</strong> Commonly used in external sorting algorithms for managing
large files that do not fit into memory.</li>
</ul>
</section>
<section class="complexity scroll-animate">
<h2 class="section-title">Time and Space Complexity</h2>
<h3>Time Complexity</h3>
<ul>
<li><strong>Best Case:</strong> <code>O(n log n)</code> – Consistent performance across all cases.
</li>
<li><strong>Average Case:</strong> <code>O(n log n)</code> – Maintains efficient performance on
average.</li>
<li><strong>Worst Case:</strong> <code>O(n log n)</code> – Efficient even in the worst-case
scenario.</li>
</ul>
<h3>Space Complexity</h3>
<p><strong>Space Complexity:</strong> <code>O(n)</code> – Requires additional space for the temporary
arrays used in the merging process.</p>
</section>
<section class="pseudo-code scroll-animate">
<h2 class="section-title">Pseudo Code</h2>
<div class="code-container">
<button class="copy-btn" onclick="copyToClipboard(this)">Copy</button>
<pre class="pseudo-code-code"><code><!-- Merge sort -->function mergeSort(arr):
if length(arr) <= 1:
return arr
mid = length(arr) / 2
left = mergeSort(arr[0:mid])
right = mergeSort(arr[mid:length(arr)])
return merge(left, right)
function merge(left, right):
result = []
while left and right are not empty:
if left[0] <= right[0]:
append left[0] to result
remove left[0]
else:
append right[0] to result
remove right[0]
append remaining elements of left and right to result
return result</code></pre>
</div>
</section>
<section class="characteristics scroll-animate">
<h2 class="section-title">Key Characteristics</h2>
<ul>
<li><strong>Stable:</strong> Merge sort is a stable sorting algorithm.</li>
<li><strong>Divide and Conquer:</strong> The algorithm utilizes the divide-and-conquer strategy
effectively.</li>
</ul>
</section>
<section class="summary scroll-animate">
<h2 class="section-title">Summary</h2>
<p>Merge sort is a powerful and efficient sorting algorithm that consistently performs at
<code>O(n log n)</code> complexity. Its stability and performance make it ideal for sorting large
datasets and is widely utilized in computer science applications.
</p>
</section>
<section class="language-code-container">
<h1 class="scroll-animate">Merge Sort Code Implementation</h1>
<div class="language-selector scroll-animate">
<button data-language="c">C</button>
<button data-language="cpp">C++</button>
<button data-language="javascript">JavaScript</button>
<button data-language="python">Python</button>
<button data-language="java">Java</button>
</div>
<pre class="inside-code-container">
<code id="code-display"></code>
</pre>
<button class="language-copy-button scroll-animate">Copy</button>
</section>
</div>
</div>
<button id="backToTopBtn" title="Go to top">↑</button>
<footer class="site-footer">
<div class="footer-container">
<p class="footer-title">Sorting Visualizer</p>
<div class="footer-links">
<a href="./about.html">About</a> |
<a href="./feedback.html">Feedback </a> |
<a href="./contact.html">Contact</a>
</div>
<p class="footer-info">© <span id="year">2024</span> Sorting Visualizer. All rights reserved.</p>
<p class="footer-credit">Made with ❤️ by Arun Neupane</p>
<p class="footer-credit">For Learning and Development</p>
</div>
</footer>
<script src="./app.js"></script>
<script>
const codeSnippets = {
javascript: `// JavaScript code for Merge Sort
function mergeSort(arr) {
if (arr.length <= 1) {
return arr;
}
const mid = Math.floor(arr.length / 2);
const left = arr.slice(0, mid);
const right = arr.slice(mid);
return merge(mergeSort(left), mergeSort(right));
}
function merge(left, right) {
let result = [], leftIndex = 0, rightIndex = 0;
while (leftIndex < left.length && rightIndex < right.length) {
if (left[leftIndex] < right[rightIndex]) {
result.push(left[leftIndex]);
leftIndex++;
} else {
result.push(right[rightIndex]);
rightIndex++;
}
}
return result.concat(left.slice(leftIndex)).concat(right.slice(rightIndex));
}
let arr = [16, 15, 15, 10, 1];
console.log('Before sorting:', arr);
arr = mergeSort(arr);
console.log('After sorting:', arr);`,
c: `// C code for Merge Sort
#include <stdio.h>
#include <stdlib.h>
void merge(int arr[], int left, int mid, int right) {
int n1 = mid - left + 1;
int n2 = right - mid;
int L[n1], R[n2];
for (int i = 0; i < n1; i++) L[i] = arr[left + i];
for (int j = 0; j < n2; j++) R[j] = arr[mid + 1 + j];
int i = 0, j = 0, k = left;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
void mergeSort(int arr[], int left, int right) {
if (left < right) {
int mid = left + (right - left) / 2;
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
merge(arr, left, mid, right);
}
}
int main() {
int arr[] = {16, 15, 15, 10, 1};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Before sorting: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
mergeSort(arr, 0, n - 1);
printf("\\nAfter sorting: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}`,
cpp: `// C++ code for Merge Sort
#include <iostream>
#include <vector>
using namespace std;
void merge(vector<int>& arr, int left, int mid, int right) {
int n1 = mid - left + 1;
int n2 = right - mid;
vector<int> L(n1), R(n2);
for (int i = 0; i < n1; i++) L[i] = arr[left + i];
for (int j = 0; j < n2; j++) R[j] = arr[mid + 1 + j];
int i = 0, j = 0, k = left;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
void mergeSort(vector<int>& arr, int left, int right) {
if (left < right) {
int mid = left + (right - left) / 2;
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
merge(arr, left, mid, right);
}
}
int main() {
vector<int> arr = {16, 15, 15, 10, 1};
cout << "Before sorting: ";
for (int num : arr) {
cout << num << " ";
}
mergeSort(arr, 0, arr.size() - 1);
cout << "\\nAfter sorting: ";
for (int num : arr) {
cout << num << " ";
}
return 0;
}`,
java: `// Java code for Merge Sort
public class SortingAlgorithm {
public static void merge(int[] arr, int left, int mid, int right) {
int n1 = mid - left + 1;
int n2 = right - mid;
int[] L = new int[n1];
int[] R = new int[n2];
for (int i = 0; i < n1; i++) L[i] = arr[left + i];
for (int i = 0; i < n2; i++) R[i] = arr[mid + 1 + i];
int i = 0, j = 0, k = left;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
public static void mergeSort(int[] arr, int left, int right) {
if (left < right) {
int mid = left + (right - left) / 2;
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
merge(arr, left, mid, right);
}
}
public static void main(String[] args) {
int[] arr = {16, 15, 15, 10, 1};
System.out.print("Before sorting: ");
for (int num : arr) {
System.out.print(num + " ");
}
mergeSort(arr, 0, arr.length - 1);
System.out.print("\\nAfter sorting: ");
for (int num : arr) {
System.out.print(num + " ");
}
}
}`,
python: `# Python code for Merge Sort
def merge(arr, left, mid, right):
n1 = mid - left + 1
n2 = right - mid
L = arr[left:left + n1]
R = arr[mid + 1:mid + 1 + n2]
i = j = k = left
while i < n1 and j < n2:
if L[i] <= R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
while i < n1:
arr[k] = L[i]
i += 1
k += 1
while j < n2:
arr[k] = R[j]
j += 1
k += 1
def mergeSort(arr, left, right):
if left < right:
mid = (left + right) // 2
mergeSort(arr, left, mid)
mergeSort(arr, mid + 1, right)
merge(arr, left, mid, right)
arr = [16, 15, 15, 10, 1]
print('Before sorting:', arr)
mergeSort(arr, 0, len(arr) - 1)
print('After sorting:', arr)
`
};
const sortBtn = document.getElementById("sort-btn");
const inputBox = document.getElementById("input-num");
const passesDiv = document.getElementById("passes");
const howto = document.getElementById("howto");
const skipBtn = document.getElementById("skip");
const fastBtn = document.getElementById("fast-btn");
let ms = 1000;
let left, right;
sortBtn.addEventListener("click", () => {
if (sortBtn.textContent == "Sorting...") return;
let input = inputBox.value.trim();
if (input == "") {
alert("Please enter some values ! ");
return;
}
ms = 1000;
displayBtn("inline");
sortBtn.textContent = "Sorting...";
const values = input.split(',');
left = values.length / 2;
right = values.length - left;
const numDiv = document.getElementById("num-div");
numDiv.innerHTML = "";
passesDiv.innerHTML = "";
howto.innerHTML = "";
howto.style.visibility = "hidden";
let pass = 1;
for (let i = 0; i < values.length; i++) {
let el = document.createElement("div");
el.className = "num-wrapper";
let li = document.createElement("div");
li.className = "num";
li.textContent = values[i];
values[i] = parseFloat(values[i]);
let li1 = document.createElement("p");
li1.classList = "ij";
li1.textContent = i;
el.appendChild(li1);
el.appendChild(li);
numDiv.appendChild(el);
}
const divs = document.querySelectorAll(".num");
let tValues = mergeSort(values);
sortedArray = tValues.join(", ");
howto.style.visibility = "visible";
howto.innerHTML = "The array is successfully sorted.There were " + values.length + " numbers and it took " + (values.length - 1) + " passes.The sorted array is : <br>" + sortedArray;
const btn = document.createElement("button");
btn.textContent = "Copy";
btn.className = "copy-btn";
btn.id = "ans-copy-btn";
btn.addEventListener("click", () => {
navigator.clipboard.writeText(sortedArray);
btn.textContent = "Copied!";
setTimeout(() => {
btn.textContent = "Copy";
}, 2000);
});
howto.appendChild(btn);
displayBtn("none");
sortBtn.textContent = "Sort";
function mergeSort(array) {
if (array.length <= 1) {
return array;
}
const mid = Math.floor(array.length / 2);
const left = mergeSort(array.slice(0, mid));
const right = mergeSort(array.slice(mid));
return merge(left, right);
}
function merge(left, right) {
const sortedArray = [];
while (left.length && right.length) {
if (left[0] < right[0]) {
sortedArray.push(left.shift());
} else {
sortedArray.push(right.shift());
}
}
// Concatenate remaining elements
return sortedArray.concat(left).concat(right);
}
});
// divide();
function divide() {
let values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
let gap = values.length;
let power = 0, counter = 0;
while (gap > 0) {
const numbersDiv = document.createElement("div");
numbersDiv.className = "numbers";
let iterator = 0;
for (let i = 0; i < Math.pow(2, power); i++) {
const numWrapper = document.createElement("div");
numWrapper.className = "numbers-wrapper";
for (let j = iterator; j < gap && counter < values.length; j++) {
const numDiv = document.createElement("div");
numDiv.textContent = values[counter];
numDiv.className = "num";
counter++;
numWrapper.appendChild(numDiv);
}
iterator = gap;
gap += gap;
gap > values.length ? gap = values.length : gap = gap;
numbersDiv.appendChild(numWrapper);
}
counter = 0;
passesDiv.appendChild(numbersDiv);
gap = parseInt(gap / 2);
power++;
}
}
</script>
<script src="./script.js"></script>
</body>
</html>