Surprising Sort

Toggle class name on click in jQuery

HTML

<div id="list">
  
</div>
<button onclick="run()">
Sort
</button>

CSS

.entry {
  display:inline-block;
  width:10px;
  height:10px;
  margin:2px;
}

JavaScript

const length = 20;

function swapElements($el1, $el2) {
    const $temp = $el1.clone();
    $temp.insertAfter($el2);
    $el2.insertAfter($el1);
    $el1.remove();
}

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

function shuffleArray(array) {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
    }
    return array;
}

function render(elements) {
	$list = $('#list');
  $list.html('');
  for(let i=0; i<elements.length; i++) {
  	$list.append(elements[i]);
  }
}


let elements = [];
for(let i=0; i<length; i++) {
	const color = Math.floor(i/length * 256);
	elements.push($(`<div id="box${i}" data-color="${color}" class="entry" style="background-color:rgb(${color}, ${color}, ${color})"></div>`));
}
elements = shuffleArray(elements);
render(elements);

async function run() {
	for(let i=0; i<length; i++) {
    for(let j=0; j<length; j++) {
      await sleep(50);
    	console.log(i,j);
      const $box1 = elements[i];
      const $box2 = elements[j];
      console.log($box1.data('color'), $box2.data('color'))
      if(parseInt($box1.data('color')) < parseInt($box2.data('color'))) {
      	console.log('swap');
        elements[j] = $box1;
        elements[i] = $box2;
        render(elements);
      }
    }
  }
}