-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
97 lines (90 loc) · 2.11 KB
/
index.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
<!DOCTYPE html>
<html>
<head>
<title>Bubble Sort</title>
<meta charset="UTF-8">
<script src=
"https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/p5.min.js"
type="text/javascript"></script>
<style>
body {
padding: 0;
}
canvas {
vertical-align: top;
}
</style>
</head>
<body>
<script type="text/javascript">
let values = [];
let w = 2;
let states = [];
function setup() {
// Create Canvas of Size Windows
// Width * Windows Height
createCanvas(1000, 700);
// Insert Random values in array
values = new Array(floor(width/w));
for(let i = 0; i < values.length; i++) {
values[i] = float(random(height));
states[i] = -1;
}
// Print Unsorted Array
print("Unsorted Array:" + values);
// Call to bubble sort function
bubbleSort(values, 0, values.length);
// Print Sorted Array
print("Sorted Array:" + values);
}
// Definition of bubble sort
async function bubbleSort(arr, start, end) {
if(start >= end) {
return;
}
for(var i = 0; i < end-1; i++) {
for(var j = 0; j < end-i-1; j++) {
if(arr[j] >= arr[j+1]) {
states[j] = 1;
// Call to swap function
await swap(arr, j, j+1);
states[j+1] = 0;
}
states[j] = 2;
}
}
return arr;
}
// Definition of draw function
function draw() {
background(51);
for(let i = 0; i < values.length; i++) {
stroke(0);
fill(255);
if(states[i] == 0) {
fill(255, 0, 0);
}
else if (states[i] == 1) {
// Element currently sorting
fill("#58FA82");
}
else {
fill(255);
}
rect(i*w, height - values[i], w, values[i]);
}
}
// Definition of swap function
async function swap(arr, a, b) {
await sleep(1);
let t = arr[a];
arr[a] = arr[b];
arr[b] = t;
}
// Definition of sleep function
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
</script>
</body>
</html>