Home  >  Article  >  Web Front-end  >  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

零下一度
零下一度Original
2017-04-28 10:08:121898browse

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>

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!

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