Hi I am writing a naive search/ brute force sorted algorithm but I am not sure how to stop it when it has sorted. I know how to algorithm works and I have written code for it, I have implemented a while(!sorted) loop but that doesnt seem to do the trick. How do I know when to stop calling the algorithm itself i.e. when its sorted. I know for things like bubble sort it is it's big O notation, so you loop n squared times but what about this sorting algorithm? Here is my failed attempt, error that I get is the webpage itself crashing, console.logs don't print out nothing loads, nothing in console.
var
cols = 100;
windowWidth = 800, windowHeight = 800,
dataWidth = windowWidth/cols,
dataStructure = new Array(cols),
colorCode = [],
sortedd = new Boolean;
//function discovered on https://stackoverflow.com/questions/951021/what-is-the-javascript-version-of-sleep
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function setup(){
createCanvas(windowWidth, windowHeight);
for(var i = 0; i < dataStructure.length; i ++){
dataStructure[i] = random(800);
colorCode[i] = "blank";
}
while(!sorted(dataStructure)){
sorted(dataStructure);
}
}
function naiveSort(arr){
for(var i = 0; i < arr.length - 1; i ++){
colorCode[i] = "red";
var temp = Math.random() * (dataStructure.length);
swap(arr, i, temp);
colorCode[i] = "red";
}
}
function sorted(arr){
for(var i = 0; i < arr.length - 1; i ++){
if(arr[i] > arr[i + 1]){
return false;
}
}
return true;
}
function swap(arr, a, b){
var temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
Ignore createCanvas, p5js library function, doesn't affect problem