-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbubblesort.html
More file actions
93 lines (86 loc) · 2.62 KB
/
bubblesort.html
File metadata and controls
93 lines (86 loc) · 2.62 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.min.js"
integrity="sha512-N4kV7GkNv7QR7RX9YF/olywyIgIwNvfEe2nZtfyj73HdjCUkAfOBDbcuJ/cTaN04JKRnw1YG1wnUyNKMsNgg3g=="
crossorigin="anonymous"
referrerpolicy="no-referrer"
></script>
<script>
const window_w = 400;
const window_h = 400;
const array_size = 100;
const fps = 30;
const asc = true;
var numbers;
function setup() {
createCanvas(window_w, window_h);
numbers = new Array(array_size);
for (let i = 0; i < numbers.length; i++) {
numbers[i] = Math.random() * (window_h - 1) + 1;
}
frameRate(fps);
}
function draw() {
background(0, 0, 0);
//Do one sorting step
numbers = bubbleStep(numbers, asc);
//Draw array
for (let i = 0; i < numbers.length; i++) {
//Line properties
let thickness = window_w / numbers.length;
let xpos = thickness * i;
let ypos = window_h;
let width = xpos;
let height = numbers[i];
let color = "#ff8800";
stroke(color);
strokeWeight(thickness);
line(xpos + thickness / 2, ypos, width + thickness / 2, height);
}
//Check if array is sorted and end loop
if (isSorted(numbers, asc)) {
console.log("Finished !");
noLoop();
}
}
function isSorted(array, asc) {
for (let i = 0; i < array.length; i++) {
if (asc) {
if (array[i] < array[i + 1]) return false;
} else {
if (array[i] > array[i + 1]) return false;
}
}
return true;
}
//One step every frame
function bubbleStep(array, asc) {
for (let i = 0; i < array.length; i++) {
if (!asc) {
if (array[i] > array[i + 1]) {
swap(array, i, i + 1);
}
} else {
if (array[i] < array[i + 1]) {
swap(array, i, i + 1);
}
}
}
return array;
}
function swap(array, index1, index2) {
let temp = array[index1];
array[index1] = array[index2];
array[index2] = temp;
}
</script>
</body>
</html>