📜  使用JavaScript的插入排序可视化

📅  最后修改于: 2021-04-17 16:37:46             🧑  作者: Mango

插入排序是一种简单的排序算法,其中从未排序部分中选取值并将其放置在已排序部分中的正确位置。

为了更多地了解它。请参阅插入排序。

通过可视化代替长代码,可以轻松理解像插入排序这样的算法。在本文中,插入排序可视化工具是使用HTML,CSS和JavaScript实现的。

先决条件:

  • 插入排序。
  • 基本的HTML,CSS和JavaScript。
  • JavaScript中的诺言。
  • JavaScript中的async / await函数。

方法:

  • Button Generate New Array使用Math.random()函数生成一个随机值数组,并根据高度来生成与该值对应的条形图。
  • 不同的颜色用于指示哪些元素未排序(天蓝色),比较(深蓝色)和已排序(浅绿色)。
  • 按钮插入使用选择排序算法对元素进行排序。
  • 最后,对元素进行排序。

例子:

  • 单击Generate New Array按钮生成一个新的随机数组。
  • 单击选择排序按钮以执行可视化。
HTML


    
  
  
     
    
    
  
  
  
  
    
Insertion Sort
    
    
    
                  Generate New Array                      
                 


CSS
.mySlides {
  display: none;
}
  
body {
  background-color: rgb(255, 235, 211);
  font-family: Verdana, sans-serif;
}
  
.head {
  margin-top: 20px;
  margin-right: 20vw;
  margin-left: 20vw;
  text-align: center;
  font-size: 30px;
  background-color: #6f459e;
  color: white;
  border-radius:19px;
  font-weight: bolder;
}
  
.data-container {
  width: 600px;
  height: 364px;
  position: relative;
  margin: 0 auto;
}
  
.bar {
  width: 28px;
  position: absolute;
  left: 0;
  bottom: 0;
  background-color: rgb(0, 183, 255);
  transition: 0.2s all ease;
}
  
.bar__id {
  position: absolute;
  top: -24px;
  width: 100%;
  text-align: center;
}
.btn1
{
padding: 12px;
font-weight: bolder; 
background-color: #6f459e; 
border-radius: 10px; 
color: white; 
font-size: 16px; 
border: white; 
margin-top: 1vw;
margin-right: 1vw;
}
.btn2
{
padding: 12px; 
font-weight: bolder; 
background-color: #6f459e; 
border-radius: 10px; 
color: white; 
font-size: 16px; 
border: white
}
#ele{
  text-align: center;
  height: 35px;
}


Javascript
const container = 
document.querySelector(".data-container");
  
// Function to generate bars
function generatebars(num = 20) {
  
   //For loop to generate 20 bars
  for (let i = 0; i < num; i += 1) {
  
    // To generate random values from 1 to 100
    const value = Math.floor(Math.random() * 100) + 1;
  
     // To create element "div"
    const bar = document.createElement("div");
  
    // To add class "bar" to "div"
    bar.classList.add("bar");
  
     // Provide height to the bar
    bar.style.height = `${value * 3}px`;
    // Translate the bar towards positive X axis 
    bar.style.transform = `translateX(${i * 30}px)`;
  
    // To create element "label"
    const barLabel = document.createElement("label");
  
    // To add class "bar_id" to "label"
    barLabel.classList.add("bar__id");
  
    // Assign value to "label"
    barLabel.innerHTML = value;
  
    // Append "Label" to "div"
    bar.appendChild(barLabel);
  
    // Append "div" to "data-container div"
    container.appendChild(bar);
  }
}
  
// Asynchronous function to perform "Insertion Sort"
  async function InsertionSort(delay = 600) {
  let bars = document.querySelectorAll(".bar");
  
  // Provide lightgreen colour to 0th bar
  bars[0].style.backgroundColor = " rgb(49, 226, 13)";
  for (var i = 1; i < bars.length; i += 1) {
  
    // Assign i-1 to j
    var j = i - 1;
  
    // To store the integer value of ith bar to key 
    var key = 
    parseInt(bars[i].childNodes[0].innerHTML);
  
    // To store the ith bar height to height
    var height = bars[i].style.height;
     
    // For selecting section having id "ele"
    var barval=document.getElementById("ele")
  
    // For dynamically Updating the selected element
      barval.innerHTML=
      `

Element Selected is :${key}

`;        //Provide darkblue color to the ith bar      bars[i].style.backgroundColor = "darkblue";            // To pause the execution of code for 600 milliseconds     await new Promise((resolve) =>     setTimeout(() => {       resolve();     }, 600)   );        // For placing selected element at its correct position      while (j >= 0 && parseInt(bars[j].childNodes[0].innerHTML) > key) {                // Provide darkblue color to the jth bar       bars[j].style.backgroundColor = "darkblue";                // For placing jth element over (j+1)th element       bars[j + 1].style.height = bars[j].style.height;       bars[j + 1].childNodes[0].innerText =        bars[j].childNodes[0].innerText;          // Assign j-1 to j       j = j - 1;          // To pause the execution of code for 600 milliseconds       await new Promise((resolve) =>         setTimeout(() => {           resolve();         }, 600)       );                // Provide lightgreen color to the sorted part       for(var k=i;k>=0;k--){         bars[k].style.backgroundColor = " rgb(49, 226, 13)";       }     }        // Placing the selected element to its correct position     bars[j + 1].style.height = height;     bars[j + 1].childNodes[0].innerHTML = key;             // To pause the execution of code for 600 milliseconds     await new Promise((resolve) =>       setTimeout(() => {         resolve();       }, 600)     );            // Provide light green color to the ith bar     bars[i].style.backgroundColor = " rgb(49, 226, 13)";   }      barval.innerHTML="

Sorted!!!

";        // To enable the button    // "Generate New Array" after final(sorted)   document.getElementById("Button1")   .disabled = false;   document.getElementById("Button1")   .style.backgroundColor = "#6f459e";      // To enable the button    // "Insertion Sort" after final(sorted)   document.getElementById("Button2")   .disabled = false;   document.getElementById("Button2")   .style.backgroundColor = "#6f459e"; }    // Call "generatebars()" function  generatebars();    // Function to generate new random array  function generate() {   window.location.reload(); }    // Function to disable the button function disable() {   // To disable the button "Generate New Array"   document.getElementById("Button1")   .disabled = true;   document.getElementById("Button1")   .style.backgroundColor = "#d8b6ff";      // To disable the button "Insertion Sort"   document.getElementById("Button2")   .disabled = true;   document.getElementById("Button2")   .style.backgroundColor = "#d8b6ff";   }


的CSS

.mySlides {
  display: none;
}
  
body {
  background-color: rgb(255, 235, 211);
  font-family: Verdana, sans-serif;
}
  
.head {
  margin-top: 20px;
  margin-right: 20vw;
  margin-left: 20vw;
  text-align: center;
  font-size: 30px;
  background-color: #6f459e;
  color: white;
  border-radius:19px;
  font-weight: bolder;
}
  
.data-container {
  width: 600px;
  height: 364px;
  position: relative;
  margin: 0 auto;
}
  
.bar {
  width: 28px;
  position: absolute;
  left: 0;
  bottom: 0;
  background-color: rgb(0, 183, 255);
  transition: 0.2s all ease;
}
  
.bar__id {
  position: absolute;
  top: -24px;
  width: 100%;
  text-align: center;
}
.btn1
{
padding: 12px;
font-weight: bolder; 
background-color: #6f459e; 
border-radius: 10px; 
color: white; 
font-size: 16px; 
border: white; 
margin-top: 1vw;
margin-right: 1vw;
}
.btn2
{
padding: 12px; 
font-weight: bolder; 
background-color: #6f459e; 
border-radius: 10px; 
color: white; 
font-size: 16px; 
border: white
}
#ele{
  text-align: center;
  height: 35px;
}

Java脚本

const container = 
document.querySelector(".data-container");
  
// Function to generate bars
function generatebars(num = 20) {
  
   //For loop to generate 20 bars
  for (let i = 0; i < num; i += 1) {
  
    // To generate random values from 1 to 100
    const value = Math.floor(Math.random() * 100) + 1;
  
     // To create element "div"
    const bar = document.createElement("div");
  
    // To add class "bar" to "div"
    bar.classList.add("bar");
  
     // Provide height to the bar
    bar.style.height = `${value * 3}px`;
    // Translate the bar towards positive X axis 
    bar.style.transform = `translateX(${i * 30}px)`;
  
    // To create element "label"
    const barLabel = document.createElement("label");
  
    // To add class "bar_id" to "label"
    barLabel.classList.add("bar__id");
  
    // Assign value to "label"
    barLabel.innerHTML = value;
  
    // Append "Label" to "div"
    bar.appendChild(barLabel);
  
    // Append "div" to "data-container div"
    container.appendChild(bar);
  }
}
  
// Asynchronous function to perform "Insertion Sort"
  async function InsertionSort(delay = 600) {
  let bars = document.querySelectorAll(".bar");
  
  // Provide lightgreen colour to 0th bar
  bars[0].style.backgroundColor = " rgb(49, 226, 13)";
  for (var i = 1; i < bars.length; i += 1) {
  
    // Assign i-1 to j
    var j = i - 1;
  
    // To store the integer value of ith bar to key 
    var key = 
    parseInt(bars[i].childNodes[0].innerHTML);
  
    // To store the ith bar height to height
    var height = bars[i].style.height;
     
    // For selecting section having id "ele"
    var barval=document.getElementById("ele")
  
    // For dynamically Updating the selected element
      barval.innerHTML=
      `

Element Selected is :${key}

`;        //Provide darkblue color to the ith bar      bars[i].style.backgroundColor = "darkblue";            // To pause the execution of code for 600 milliseconds     await new Promise((resolve) =>     setTimeout(() => {       resolve();     }, 600)   );        // For placing selected element at its correct position      while (j >= 0 && parseInt(bars[j].childNodes[0].innerHTML) > key) {                // Provide darkblue color to the jth bar       bars[j].style.backgroundColor = "darkblue";                // For placing jth element over (j+1)th element       bars[j + 1].style.height = bars[j].style.height;       bars[j + 1].childNodes[0].innerText =        bars[j].childNodes[0].innerText;          // Assign j-1 to j       j = j - 1;          // To pause the execution of code for 600 milliseconds       await new Promise((resolve) =>         setTimeout(() => {           resolve();         }, 600)       );                // Provide lightgreen color to the sorted part       for(var k=i;k>=0;k--){         bars[k].style.backgroundColor = " rgb(49, 226, 13)";       }     }        // Placing the selected element to its correct position     bars[j + 1].style.height = height;     bars[j + 1].childNodes[0].innerHTML = key;             // To pause the execution of code for 600 milliseconds     await new Promise((resolve) =>       setTimeout(() => {         resolve();       }, 600)     );            // Provide light green color to the ith bar     bars[i].style.backgroundColor = " rgb(49, 226, 13)";   }      barval.innerHTML="

Sorted!!!

";        // To enable the button    // "Generate New Array" after final(sorted)   document.getElementById("Button1")   .disabled = false;   document.getElementById("Button1")   .style.backgroundColor = "#6f459e";      // To enable the button    // "Insertion Sort" after final(sorted)   document.getElementById("Button2")   .disabled = false;   document.getElementById("Button2")   .style.backgroundColor = "#6f459e"; }    // Call "generatebars()" function  generatebars();    // Function to generate new random array  function generate() {   window.location.reload(); }    // Function to disable the button function disable() {   // To disable the button "Generate New Array"   document.getElementById("Button1")   .disabled = true;   document.getElementById("Button1")   .style.backgroundColor = "#d8b6ff";      // To disable the button "Insertion Sort"   document.getElementById("Button2")   .disabled = true;   document.getElementById("Button2")   .style.backgroundColor = "#d8b6ff";   }

输出: