I'm trying to make a bubble sort algorithm using HTML, CSS and JS (jQuery). The idea is to swap the height of the items to sort them by height (obvs).
Somehow my code gets me stuck in an infinite loop. I was hoping someone could help me identify the problem. Thanks in advance!
var el = $('#item_parent');
var items = [];
//Genrate elements
for(let i = 0; i < 5; i++){
let rand = Math.floor(Math.random() * 300) + 1;
el.append("<div class='item d-flex justify-content-between' data-height='"+rand+"' style='height: "+rand+"px; flex: 1; margin: 0 5px;'></div>");
}
//Populating the array with the elements
items = $(".item");
var sorted = false;
while(!sorted){
sorted = true;
for (let i = 0; i < items.length - 1; i++){
if ($(items[i]).data('height') > $(items[i+1]).data('height')){
console.log($(items[i]).data('height') + " is greater than " + $(items[i+1]).data('height') + ". Swapping");
swapHeight(items, i, i+1);
sorted = false;
}
}
}
function swapHeight(elArray, firstIndex, secondIndex){
let temp = $(elArray[firstIndex]).data('height');
$(elArray[firstIndex]).css('height', $(elArray[secondIndex]).data('height') + "px");
$(elArray[secondIndex]).css('height', temp + "px");
}
data('height'), try usingdataset.heightand also make sure that you swap both the dataset.height and the css style height. It looks like you are only swapping the style height, which means that the if() test will not see any changes.