<div id="content">
  <canvas id="original"></canvas>
  <div id="longitud"></div>
  <button id="btn1" onclick="startBubbleSort()">BubbleSort</button>
  <button id="btn2" onclick="startSelectionSort()">SelectionSort</button><br/>
  <canvas id="orden1"></canvas>
   <div id="loops1"></div>
  <canvas id="orden2"></canvas>
   <div id="loops2"></div>
</div>
let orig = document.getElementById('original');
let ord1 = document.getElementById('orden1');
let ord2 = document.getElementById('orden2');
orig.width = 600;
orig.height = 150;
let ms = 1000/30;
let canvasHeight = orig.height;
let canvasWidth = orig.width;
ord1.width = canvasWidth;
ord1.height = canvasHeight;
ord2.width = canvasWidth;
ord2.height = canvasHeight;
let ctx = orig.getContext('2d');
let ctx1 = ord1.getContext('2d');
let ctx2 = ord2.getContext('2d');
let arr = [];
let arr1 = [];
rdmArr(arr);
arr1 = arr.concat();
let b = 0;
let b1 = b;
ctx.transform(1, 0, 0, -1, 0, canvasHeight);
ctx1.transform(1, 0, 0, -1, 0, canvasHeight);
ctx2.transform(1, 0, 0, -1, 0, canvasHeight);
draw(ctx, arr);
document.getElementById('longitud').innerText = 'Longitud array: ' + arr.length;
let k = 0;
function startBubbleSort(){
  let intervalo1 = setInterval(function(){
    bubbleSort(arr);
    check(arr, intervalo1);
    draw(ctx1, arr, canvasHeight);
  }, ms);
}
function startSelectionSort(){
  let intervalo2 = setInterval(function(){
    selectionSort(arr1);
    check(arr1, intervalo2);
    draw(ctx2, arr1, canvasHeight);
  }, ms)
}

function bubbleSort(arr){
  for(let i = 0; i < arr.length - 1; i++){
      if(arr[i] > arr[i+1]){
        let temp = arr[i];
        arr[i] = arr[i+1];
        arr[i+1] = temp;
      }
    b++;
    document.getElementById('loops1').innerText = 'BubbleSort: Accesos: ' + b;
    }
}
function searchMin(arr, start){
  let min = {};
  min.value = start;
  for(let i = start; i < arr.length; i++){
    if(arr[i] < min.value){
      min.value = arr[i];
      min.index = i;
    }
    b1++;
  document.getElementById('loops2').innerText = 'SelectionSort: Accesos: ' + b1;
  }
  return min;
}



function selectionSort(arr){
  let temp = arr[k];
  let obj = searchMin(arr, k);
  arr[k] = obj.value;
  arr[obj.index] = temp;
  k++;
}

function rdmArr(arr){
  for (let i = 0; i < canvasWidth; i++){
    arr[i] = Math.random()*canvasHeight;
  }
}

function check(arr, intervalo){
  let t = false;
  for(let i = 0; i < arr.length - 1; i++){
      if(arr[i] > arr[i+1]){
        t = true;
        break;
      }
     }
    if(t == false){
      clearInterval(intervalo);
    }
}

function draw(ctx, arr){
  ctx.clearRect(0, 0, canvasWidth, canvasHeight);
  ctx.strokeStyle = 'red';
  ctx.beginPath();
  for(let i = 0; i < arr.length; i++){
    ctx.moveTo(i, 0);
    ctx.lineTo(i, arr[i]);
  }
  ctx.stroke();
}

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

  1. https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js