search
HomeWeb Front-endJS TutorialJS implements bubble sort, insertion sort and quick sort and sorts the output

I was asked this question in an interview, but I was really confused and couldn't answer it. Later, I sorted it out through JS, and combined it with the html code to make a text box, and sorted the input content from the text box and output it. Once again, I will not describe it, but I will show it to you through a piece of code:

The following is the code:

index.html
 
 <!DOCTYPE html>
 <html>
 <head>
   <title>Sorting</title>
   <link rel="stylesheet" type="text/css" href="style.css">
 </head>
 <body>
  
   <!--主要页面结构-->
   <div class="container">
     <input type="text" name="number" id="number" placeholder="Please enter 10 numbers(don&#39;t leave space)" />
     <a href="javascript:void()" class="sortbtn" id="resultBtn">Sort</a>
     <label class="title">After Sorted:</label>
  
     <!--以下三个label分别显示冒泡,插入,快速排序的结果-->
     <label class="result" for="bubblesort"></label>
     <label class="result" for="insertsort"></label>
     <label class="result" for="quicksort"></label>
   </div>
   <!--end-->
    
   <script type="text/javascript" src="script.js"></script>
 </body>
 </html>

Let’s write some style to this page, otherwise it will not look good.

style.css
 
 *{
   margin: 0;
   padding: 0;
   list-style: none;
 }
 .container{
   width: 400px;
   margin: 100px auto;
 }
 input[type="text"]{
   display: block;
   width: 400px;
   height: 40px;
   text-align: center;
   line-height: 40px;
   outline: none;
   font-size: 14px;
   border-radius: 15px;
   border: 1px solid #aaaaaa;
 }
 .sortbtn{
   display: block;
   width: 200px;
   height: 34px;
   text-align: center;
   line-height: 34px;
   border: 1px solid black;
   border-radius: 10px;
   text-decoration: none;
   color: black;
   margin-left: 100px;
   margin-top: 30px;
 }
 .sortbtn:hover{
   display: block;
   background-color: black;
   color: #ffffff;
 }
 label{
   display: block;
   width: 200px;
   text-align: center;
   margin-left: 100px;
   margin-top: 20px;
   font-size: 20px;
 }

Then the main functions are implemented.

script.js
 
window.onload = function(){
  var btn = document.getElementById("resultBtn");      //结果输出按钮
  var inputnum = document.getElementById("number");    //数字输入框
  var resultlbl =document.getElementsByTagName("label");  //结果显示的label 
  var i,j,temp;
 
  //冒泡排序
  var bubble = function(arr){
    for(i=0;i<9;i++){
      for(j=0;j<9-i;j++){
        if(arr[j] > arr[j+1]){
          temp = arr[j];
          arr[j] = arr[j+1];
          arr[j+1] = temp;
        }
      }
    }
    return arr;
  }
 
  //插入排序
  var insersort = function(arr){
    for(i=1;i<10;i++){
      temp = arr[i];
      j = i;
      while(j > 0 && arr[j-1] > temp){
        arr[j] = arr[j-1];
        j--;
      }
      arr[j] = temp;
    }
    return arr;
  }
 
  //快速排序
  var quicksort = function(arr){
    var basenum,basenumIndex;
    var left = [];
    var right = [];
 
    if(arr.length <= 1){
      return arr;
    }
    //基准数的位置
    basenumIndex = Math.floor(arr.length/2);
    basenum = arr.splice(basenumIndex,1)[0];
    for(i=0;i<arr.length;i++){
      if(arr[i] < basenum){
        left.push(arr[i]);
      }
      else{
        right.push(arr[i]);
      }
     }
     //递归调用
     return quicksort(left).concat([basenum],quicksort(right));
   }
  
   //判断输入的值类型是否为数字
   function isNum(num){
    var reNum =/^[0-9]+$/;
    return (reNum.test(num)); 
}
  
   //按钮点击事件
   btn.onclick = function(){
     //判断输入的值的类型和长度以及是否为空
     if(!isNum(inputnum.value) || inputnum.value == "" || inputnum.value.length > 10 || inputnum.value.length < 10){
       resultlbl[0].innerHTML = "Your format is wrong![Must Be 10 numbers]";
       resultlbl[0].style.color = "red";
     }
     else{
       resultlbl[0].innerHTML = "After Sorted:";
       resultlbl[0].style.color = "black";
       var inputstream = inputnum.value.toString();  //将输入的内容转换为字符串
       var data = inputstream.split("");        //将转换的字符串分割,相当于转化为数组
        
       //结果输出
       resultlbl[1].innerHTML = "BubbleSort:" + "<br/>" + bubble(data);
       resultlbl[2].innerHTML = "InsertSort:" + "<br/>" + insersort(data);
       resultlbl[3].innerHTML = "QuickSort:" + "<br/>" + quicksort(data);
     }
   }
 }

The final effect is like this:

Without input, a quiet text box, a quiet button and a label:

JS implements bubble sort, insertion sort and quick sort and sorts the output

The input is not a number, the tens digit is not entered or exceeds the tens digit, or is empty. After clicking the button, an error will be prompted:

is empty:

JS implements bubble sort, insertion sort and quick sort and sorts the output

is not a number and has less than ten digits:

JS implements bubble sort, insertion sort and quick sort and sorts the output

exceeds tens digits:

JS implements bubble sort, insertion sort and quick sort and sorts the output

Enter the correct one Case:

JS implements bubble sort, insertion sort and quick sort and sorts the output

Tips: No spaces between the numbers you enter, no spaces between the numbers you enter, no spaces between the numbers you enter, important things Say it three times

It should be noted that the number entered in the text box can only be a one-digit number (0-9). For the sorting method of two-digit or even more-digit numbers, please continue to follow this website. Hope these contents are helpful to everyone.


For more JS implementation of bubble sort, insertion sort and quick sort and sorted output related articles, please pay attention to the PHP Chinese website!


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)