I tried to implement a mergesort algorithm but the array isn’t getting sorted for some reason.The expected output is a sorted array of lines displayed on the browser window.
Here is my code
var values = []
function setup(){
createCanvas(600,400);
values.length = width;
for(let i=0; i<values.length; i++){
values[i] = random(height);
}
mergesort(values, 0, values.length-1)
}
function draw(){
background(0);
for (let i=0; i< values.length; i++){
stroke(255,0,255);
line(i, height, i, height - values[i]);
}
}
function mergesort(arr, start, end){
if (start < end){
let middle = (start + (end-1))/2;
merge(arr, start, middle, end);
mergesort(arr, start, middle);
mergesort(arr, middle +1, end);
}
}
function merge(arr, start, middle, end){
let sizeL = middle-start +1;
let sizeR = end - middle;
let arrL = [];
let arrR = [];
//var arr1 = [];
for (let i = start; i < sizeL; i++)
arrL.push(arr[i])
for (let j = start; j < sizeR ; j++)
arrR.push(arr[j])
let a = start;
let b = start;
let k = start + 1;
while ( a< sizeL && b < sizeR){
if (arrL[a] <= arrR[b]){
arr[k] = arrL[a];
a++;
}
else{
arr[k] = arrR[b];
b++;
}
k++;
}
while(a < sizeL){
arr[k] = arrL[a];
a++;
k++;
}
while(b < sizeR) {
arr[k] = arrR[b];
b++;
k++;
}
//return arr1;
}