-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsorting.js
More file actions
656 lines (578 loc) · 17.9 KB
/
sorting.js
File metadata and controls
656 lines (578 loc) · 17.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
let { delayTime, swap, btn } = require("./utils");
const {
disableSortingBtn,
enableSortingBtn,
disableSizeSlider,
disableSpeedSlider,
enableSpeedSlider,
enableSizeSlider,
disableNewArrayBtn,
enableNewArrayBtn,
enableStopSortingBtn,
disableStopSortingBtn,
} = require("./helper");
const { createNewArray } = require("./controllers");
let delay = 260;
let arraySize = document.querySelector("#size_input");
let hasPressedStop = false;
// Call to display bars right when you visit the site
createNewArray();
let delayElement = document.querySelector("#speed_input");
// Event listener to update the bars on the UI
if (arraySize) {
arraySize.addEventListener("input", function () {
// console.log(arraySize.value, typeof arraySize.value);
createNewArray(parseInt(arraySize.value));
});
}
// Event listener to update delay time
if (delayElement) {
delayElement.addEventListener("input", function () {
// console.log(delayElement.value, typeof delayElement.value);
delay = 320 - parseInt(delayElement.value);
});
}
// Selecting newarray button from DOM and adding eventlistener
if (btn.newArrayButton) {
btn.newArrayButton.addEventListener("click", function () {
hasPressedStop = false;
enableSpeedSlider();
console.log("From newArray " + arraySize.value);
console.log("From newArray " + delay);
enableSortingBtn();
enableSizeSlider();
createNewArray(arraySize.value);
});
}
if (btn.stopSortingButton) {
btn.stopSortingButton.addEventListener("click", function () {
disableSortingBtn();
disableSizeSlider();
hasPressedStop = true;
});
}
// ------------------HEAP SORT-------------------------
/**
* @param {NodeListOf<Element>} arr
* @param {int} n
* @param {int} i
*/
async function heapify(arr, n, i) {
let largest = i;
const l = 2 * i + 1;
const r = 2 * i + 2;
// Compare with left child
if (
l < n &&
parseInt(arr[l].style.height) > parseInt(arr[largest].style.height)
) {
largest = l;
}
// Compare with right child
if (
r < n &&
parseInt(arr[r].style.height) > parseInt(arr[largest].style.height)
) {
largest = r;
}
// If the largest is not the root
if (largest !== i) {
// Swap elements
swap(arr[i], arr[largest]);
// Recursively heapify the affected sub-tree
await heapify(arr, n, largest);
}
}
/**
* @param {NodeListOf<Element>} arr
* @param {int} n
*/
async function heapSort(arr, n) {
// Build max heap
for (let i = Math.floor(n / 2) - 1; i >= 0; i--) {
if (hasPressedStop) {
return;
}
await heapify(arr, n, i);
}
// Extract elements from the heap one by one
for (let i = n - 1; i > 0; i--) {
if (hasPressedStop) {
return;
}
// Swap root with the last element
swap(arr[0], arr[i]);
arr[i].style.background = "green";
await delayTime(delay);
// Heapify the reduced heap
await heapify(arr, i, 0);
}
}
// ------------------INSERTION SORT-------------------------
/**
* @param {NodeListOf<Element>} ele
*/
async function insertion(ele) {
ele[0].style.background = "green";
for (let i = 1; i < ele.length; i++) {
if (hasPressedStop) {
return;
}
let j = i - 1;
let key = ele[i].style.height;
ele[i].style.background = "blue";
await delayTime(delay);
if (hasPressedStop) {
return;
}
while (j >= 0 && parseInt(ele[j].style.height) > parseInt(key)) {
if (hasPressedStop) {
return;
}
ele[j].style.background = "blue";
ele[j + 1].style.height = ele[j].style.height;
j--;
await delayTime(delay);
if (hasPressedStop) {
return;
}
// Reset color for visualization
for (let k = i; k >= 0; k--) {
ele[k].style.background = "green";
}
}
ele[j + 1].style.height = key;
ele[i].style.background = "green";
}
}
// ------------------MERGE SORT-------------------------
// Function to merge two subarrays within 'ele'
// This function is responsible for merging two subarrays within the main array during the merge sort process. It also visualizes the merging process by changing the background color of elements.
/**
* @param {NodeListOf<Element>} arr
* @param {int} low
* @param {int} mid
* @param {int} high
* represent the indices that define the two subarrays to be merged.
*/
async function merge(arr, low, mid, high) {
// calculates the number of elements in the left subarray
const n1 = mid - low + 1;
// calculates the number of elements in the right subarray
const n2 = high - mid;
// created to store the elements of the subarrays.
let left = new Array(n1);
let right = new Array(n2);
// Populating the 'left' array
for (let i = 0; i < n1; i++) {
if (hasPressedStop) {
return;
}
await delayTime(delay);
arr[low + i].style.background = "orange";
left[i] = arr[low + i].style.height;
}
// Populating the 'right' array
for (let i = 0; i < n2; i++) {
if (hasPressedStop) {
return;
}
await delayTime(delay);
arr[mid + 1 + i].style.background = "cyan";
right[i] = arr[mid + 1 + i].style.height;
}
await delayTime(delay);
let i = 0,
j = 0,
k = low;
// Merging the two arrays
while (i < n1 && j < n2) {
if (hasPressedStop) {
return;
}
await delayTime(delay);
// Comparing elements and updating styles
if (parseInt(left[i]) <= parseInt(right[j])) {
arr[k].style.background =
n1 + n2 === arr.length ? "green" : "lightgreen";
arr[k].style.height = left[i];
i++;
} else {
arr[k].style.background =
n1 + n2 === arr.length ? "green" : "lightgreen";
arr[k].style.height = right[j];
j++;
}
k++;
}
// Copy the remaining elements from 'left' and 'right'
while (i < n1) {
if (hasPressedStop) {
return;
}
await delayTime(delay);
arr[k].style.background =
n1 + n2 === arr.length ? "green" : "lightgreen";
arr[k].style.height = left[i];
i++;
k++;
}
while (j < n2) {
if (hasPressedStop) {
return;
}
await delayTime(delay);
arr[k].style.background =
n1 + n2 === arr.length ? "green" : "lightgreen";
arr[k].style.height = right[j];
j++;
k++;
}
}
// Recursive function to perform merge sort on 'ele'
// The function recursively divides the array into smaller subarrays until it reaches the base case (when the subarray size is 1 or 0).
/**
* @param {NodeListOf<Element>} arr
* @param {int} l
* @param {int} r
*/
async function mergeSort(arr, l, r) {
// l and r represent the left and right boundaries of the subarray to be sorted.
if (l >= r) {
// Base case: sorting complete
return;
}
const m = l + Math.floor((r - l) / 2);
await mergeSort(arr, l, m);
await mergeSort(arr, m + 1, r);
await merge(arr, l, m, r);
}
/**
* @param {NodeListOf<Element>} arr
* @param {int} l
* @param {int} r
*/
// Function to enable UI elements after sorting is done
async function performMergeSort(arr, l, r) {
// track whether the user has stopped the sorting process.
let hasPressedStop = false;
await mergeSort(arr, l, r);
if (hasPressedStop) {
disableSpeedSlider();
} else {
enableSortingBtn();
enableSizeSlider();
}
enableNewArrayBtn();
disableStopSortingBtn();
}
// ------------------QUICK SORT-------------------------
/**
*
* @param {NodeListOf<Element>} ele
* @param {int} l
* @param {int} r
*/
async function partitionLomuto(ele, l, r) {
if (ele) {
let i = l - 1;
ele[r].style.background = "cyan"; // Pivot
for (let j = l; j <= r - 1; j++) {
if (hasPressedStop) {
return;
}
ele[j].style.background = "yellow"; // Current element
await delayTime(delay);
if (hasPressedStop) {
return;
}
const currentHeight = parseInt(ele[j].style.height);
const pivotHeight = parseInt(ele[r].style.height);
if (currentHeight < pivotHeight) {
i++;
swap(ele[i], ele[j]);
// Color
ele[i].style.background = "orange";
if (i !== j) ele[j].style.background = "orange";
await delayTime(delay);
} else {
// Color if not less than pivot
ele[j].style.background = "pink";
}
}
i++;
await delayTime(delay);
// Swap pivot element into its correct position
swap(ele[i], ele[r]);
// Color
ele[r].style.background = "pink";
ele[i].style.background = "green";
await delayTime(delay);
// Reset colors
for (const element of ele) {
if (element.style.background !== "green") {
element.style.background = "#e43f5a";
}
}
return i; // Return the pivot index
}
}
/**
*
* @param {NodeListOf<Element>} ele
* @param {int} l
* @param {int} r
*/
async function quickSort(ele, l, r) {
if (l < r) {
let pivotIndex = await partitionLomuto(ele, l, r);
await Promise.all([
quickSort(ele, l, pivotIndex - 1),
quickSort(ele, pivotIndex + 1, r),
]);
} else {
// Highlight the already sorted segments
if (l >= 0 && r >= 0 && l < ele.length && r < ele.length) {
ele[r].style.background = "green";
ele[l].style.background = "green";
}
}
}
// ------------------BUBBLE SORT-------------------------
/**
*
* @param {NodeListOf<Element>} ele
*/
async function bubble(ele) {
if (!ele) return;
for (let i = 0; i < ele.length - 1; i++) {
for (let j = 0; j < ele.length - i - 1; j++) {
if (hasPressedStop === true) {
return; // Exit early if the stop button is pressed
}
ele[j].style.background = "cyan";
ele[j + 1].style.background = "cyan";
if (
parseInt(ele[j].style.height) >
parseInt(ele[j + 1].style.height)
) {
await delayTime(delay);
swap(ele[j], ele[j + 1]);
}
ele[j].style.background = "#e43f5a";
ele[j + 1].style.background = "#e43f5a";
}
ele[ele.length - 1 - i].style.background = "green";
}
ele[0].style.background = "green";
}
// ------------------SELECTION SORT-------------------------
/**
*
* @param {NodeListOf<Element>} ele
*/
async function selection(ele) {
for (let i = 0; i < ele.length; i++) {
if (hasPressedStop == true) {
return;
}
let min_index = i;
// Change color of the bar being compared
ele[i].style.background = "lightgreen";
for (let j = i + 1; j < ele.length; j++) {
if (hasPressedStop == true) {
return;
}
// Change color of current bar
ele[j].style.background = "cyan";
await delayTime(delay);
if (hasPressedStop == true) {
return;
}
if (
parseInt(ele[j].style.height) <
parseInt(ele[min_index].style.height)
) {
if (min_index !== i) {
// new min_index is found so change prev min_index color back to normal
ele[min_index].style.background = "#e43f5a";
}
min_index = j;
} else {
// if the currnent comparision is more than min_index change is back to normal
ele[j].style.background = "#e43f5a";
}
}
await delayTime(delay);
if (hasPressedStop == true) {
return;
}
swap(ele[min_index], ele[i]);
// change the min element index back to normal as it is swapped
ele[min_index].style.background = "#e43f5a";
// change the sorted elements color to green
ele[i].style.background = "green";
}
}
const handleHeapSort = () => {
let arr = document.querySelectorAll(".bar");
let n = arr.length;
let hasPressedStop = false;
disableSortingBtn();
disableSizeSlider();
disableNewArrayBtn();
enableStopSortingBtn();
// Perform Heap Sort and handle the promise
heapSort(arr, n)
.then(() => {
arr[0].style.background = "green";
if (hasPressedStop) {
disableSpeedSlider();
} else {
enableSortingBtn();
enableSizeSlider();
}
enableNewArrayBtn();
disableStopSortingBtn();
})
.catch((error) => {
console.error("An error occurred during sorting:", error);
// Handle the error condition if needed
});
};
const handleInsertion = () => {
const ele = document.querySelectorAll(".bar");
disableSortingBtn();
disableSizeSlider();
disableNewArrayBtn();
enableStopSortingBtn();
// Perform Insertion Sort and handle UI updates
insertion(ele)
.then(() => {
if (hasPressedStop) {
disableSpeedSlider();
} else {
enableSortingBtn();
enableSizeSlider();
}
enableNewArrayBtn();
disableStopSortingBtn();
})
.catch((error) => {
console.error("An error occurred during sorting:", error);
// Handle the error condition if needed
});
};
const handleSelection = () => {
const ele = document.querySelectorAll(".bar");
hasPressedStop = false;
disableSortingBtn();
disableSizeSlider();
disableNewArrayBtn();
enableStopSortingBtn();
selection(ele)
.then(() => {
if (hasPressedStop) {
disableSpeedSlider();
} else {
enableSortingBtn();
enableSizeSlider();
}
enableNewArrayBtn();
disableStopSortingBtn();
})
.catch((error) => {
// Handle any errors that might occur during the sorting process
console.error("An error occurred:", error);
// Additional error handling logic if needed
});
};
const handleMergeSort = () => {
// It retrieves the array elements from the DOM.
let arr = document.querySelectorAll(".bar");
let l = 0;
let r = parseInt(arr.length) - 1;
// Disable UI elements during sorting
disableSortingBtn();
disableSizeSlider();
disableNewArrayBtn();
enableStopSortingBtn();
// Call the async function within a regular function
if (arr) {
performMergeSort(arr, l, r);
}
};
const handleQuickSort = () => {
const ele = document.querySelectorAll(".bar");
const l = 0;
const r = ele.length - 1;
let hasPressedStop = false;
disableSortingBtn();
disableSizeSlider();
disableNewArrayBtn();
enableStopSortingBtn();
// Perform Quick Sort and handle UI updates
quickSort(ele, l, r)
.then(() => {
if (hasPressedStop) {
disableSpeedSlider();
} else {
enableSortingBtn();
enableSizeSlider();
}
enableNewArrayBtn();
disableStopSortingBtn();
})
.catch((error) => {
console.error("An error occurred during sorting:", error);
});
};
const handleBubbleSort = async () => {
const ele = document.querySelectorAll(".bar");
disableSortingBtn();
disableSizeSlider();
disableNewArrayBtn();
enableStopSortingBtn();
try {
await bubble(ele);
if (hasPressedStop) {
disableSpeedSlider();
disableStopSortingBtn();
} else {
enableSortingBtn();
enableSizeSlider();
}
enableNewArrayBtn();
disableStopSortingBtn();
} catch (error) {
console.error("An error occurred during sorting:", error);
// Handle error
}
};
if (btn.inSortbtn) {
btn.inSortbtn.addEventListener("click", handleInsertion);
}
if (btn.heapSortbtn) {
btn.heapSortbtn.addEventListener("click", handleHeapSort);
}
if (btn.bubSortbtn) {
btn.bubSortbtn.addEventListener("click", handleBubbleSort);
}
if (btn.mergeSortbtn) {
btn.mergeSortbtn.addEventListener("click", handleMergeSort);
}
if (btn.quickSortbtn) {
btn.quickSortbtn.addEventListener("click", handleQuickSort);
}
if (btn.selectionSortbtn) {
btn.selectionSortbtn.addEventListener("click", handleSelection);
}
module.exports = {
bubble,
quickSort,
handleMergeSort,
heapSort,
selection,
insertion,
performMergeSort,
};