Home > Web Front-end > JS Tutorial > Intuitively understand the bubble sort algorithm implemented with js and count the number of adjacent number exchanges

Intuitively understand the bubble sort algorithm implemented with js and count the number of adjacent number exchanges

零下一度
Release: 2017-04-28 10:08:12
Original
1922 people have browsed it

This article mainly introduces the bubble sorting method implemented by JavaScript and counts the number of adjacent number exchanges. It analyzes the implementation skills of JavaScript bubble sorting and the statistical method for the number of exchanges in the form of examples, so as to facilitate a more intuitive understanding of risk. Bubble sorting algorithm, friends who need it can refer to

This article describes the bubble sorting method implemented in JavaScript and counts the number of neighbor exchanges. Share it with everyone for your reference, the details are as follows:

<html>
 <head>JS冒泡排序</head>
 <body>
  <script>
   var arr=[-1,-2,-30,-4,-5,-6];
   var flag=false;     //判断相邻两个数是否交换过
   var n=0;      //计算交换次数
   for(var i=0;i<arr.length-1;i++){    //i表示的是每次找出来的最大或最小数需要的次数
    for(var j=0;j<arr.length-i-1;j++){
     if(arr[j]>arr[j+1]){
      var temp=arr[j];
      arr[j]=arr[j+1];
      arr[j+1]=temp;
      flag=true;
     }
     if(flag){
      flag=false;
      n++;
     }else{
      continue;
     }
    }
   }
   document.write("n="+n+"<br />");
     document.write("总共交换了"+n+"次后的结果是:"+"<br />");
   for(var k=0;k<arr.length;k++){
    document.writeln(arr[k]+" ");
   }
  </script>
 </body>
</html>
Copy after login

The operation effect diagram is as follows:

The above is the detailed content of Intuitively understand the bubble sort algorithm implemented with js and count the number of adjacent number exchanges. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template