<h1>Sort Visualizer with Generators Demo</h1>
<div class="buttons">
  <button id="startBtn">Start Sorting</button>
  <button id="stepBtn" disabled>Step</button>
  <button id="resetBtn" disabled>Reset</button>
</div>
<div class="array-container" id="arrayContainer"></div>
body {
  font-family: Arial, sans-serif;
  text-align: center;
  padding: 20px;
}
.array-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
.array-box {
  width: 50px;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 5px;
  background-color: #f0f0f0;
  border: 1px solid #ddd;
  font-weight: bold;
  font-size: 18px;
}
.array-box.swapped {
  background-color: #ffd700; /* Highlight swapped elements */
}
.buttons {
  margin-top: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}
.buttons button {
  margin: 0 10px;
  padding: 10px 20px;
  font-size: 16px;
}
let arr = [5, 1, 4, 2, 3];
let gen;
let i, j;

function* bubbleSort(array) {
  for (i = 0; i < array.length - 1; ++i) {
    let swapped = false;
    for (j = 0; j < array.length - i - 1; ++j) {
      if (array[j] > array[j + 1]) {
        [array[j], array[j + 1]] = [array[j + 1], array[j]];
        swapped = true;
        yield {array: array.slice(), swappedIndices: [j, j + 1]};
      }
    }
    if (!swapped) break;
  }
  return array;
}

function renderArray(array, swappedIndices = []) {
  const arrayContainer = document.getElementById('arrayContainer');
  arrayContainer.innerHTML = '';

  array.forEach((value, index) => {
    const box = document.createElement('div');
    box.className = 'array-box';
    box.textContent = value;

    if (swappedIndices.includes(index)) {
      box.classList.add('swapped');
    }
    arrayContainer.appendChild(box);
  });
}

function startSorting() {
  gen = bubbleSort(arr);
  document.getElementById('stepBtn').disabled = false;
  document.getElementById('resetBtn').disabled = false;
}

function stepSorting() {
  const result = gen.next();
  if (!result.done) {
    renderArray(result.value.array, result.value.swappedIndices);
  } else {
    renderArray(result.value);
    document.getElementById('stepBtn').disabled = true;
  }
}

function resetSorting() {
  arr = [5, 1, 4, 2, 3]; 
  renderArray(arr); 
  document.getElementById('stepBtn').disabled = true;
  document.getElementById('resetBtn').disabled = true;
}

document.getElementById('startBtn').addEventListener('click', startSorting);
document.getElementById('stepBtn').addEventListener('click', stepSorting);
document.getElementById('resetBtn').addEventListener('click', resetSorting);

renderArray(arr);

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.