I am writing javascript code to do a naive sort for an array of values, however, I am getting an issue in my while loop where it crashes. It happens at
while(!sorted(dataStructure)){
naiveSort(dataStructure);
}
I want it so that if each element from i to end is less than the following one, sorted returns true, therefore the naive sort algorithm ends. There may be one or two things like createCanvas(800, 800); These are just methods from the p5js library but none of it is used in the algorithm.
naiveSort.js
function setup(){
createCanvas(800, 800);
for( var i = 0; i < dataStructure.length; i ++){
dataStructure[i] = random(800);
colorCode[i] = "blank";
}
while(!sorted(dataStructure)){
naiveSort(dataStructure);
}
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function swap(arr, a, b){
var temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
async function naiveSort(arr){
for(var i = 0; i < arr.length; i ++){
temp = Math.random() * ((arr.length - 1) - 0) + 0;
swap(arr, i, temp);
await sleep(10);
}
}
function sorted(arr){
for(var i = 1; i < arr.length-1; i ++){
if(arr[i] > arr[i+1]){
return false;
}
}
return true;
}
function paint(col, rgb){
for(var i = 0; i < dataStructure.length; i ++){
if(colorCode[i] == col){
stroke(0);
fill(rgb);
rect(i * dataWidth, 800 - dataStructure[i], dataWidth, dataStructure[i]);
}
}
}
function draw(){
background(51);
paint("red", color(255, 0, 0));
paint("green", color(0, 255, 0));
paint("blank", color(255));
}
index.html
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>p5.js example</title>
<style>
body {
padding: 0;
margin: 0;
}
</style>
<script src="../p5.js"></script>
<script src="naiveSort.js"></script>
</head>
<body>
</body>
</html>
naiveSortfunction is asynchronous and returns a promise, but you do neverawaitthat.awaitwith the delay to work properly before you will see any results.