Home > Article > Web Front-end > How to implement bubble sort in JavaScript in an encapsulated manner
Recently, the editor is studying Jiang Kun's JavaScript video, which talks about the method of implementing bubble sorting in js, and achieves good encapsulation and flexible changes. For specific content, please see the text.
Unencapsulated code
1. Once the core code in this code is understood, it can be completed easily.
<script type="text/javascript"> var arr=[1,6,3]; //冒泡 for(var i=0;i<arr.length;i++){ for(var j=0;j<arr.length-1-i;j++){ //核心排序 if(arr[j]>arr[j+1]){ var t=arr[j]; arr[j]=arr[j+1]; arr[j+1]=t; } } } alert(arr); </script>
Running display:
Regarding the parameter passing part, the decision is between ascending order and descending order method f. There are two methods. The default is to use ascending order without adding the method parameter of f, as follows Code:
<script type="text/javascript"> var arr=[1,6,3]; //冒泡--添加了封装性的方法 var mySort=function(arr,f){ for(var i=0;i<arr.length;i++){ for(var j=0;j<arr.length-1-i;j++){ //核心排序依据 if(f(arr[j],arr[j+1])>0){ var t=arr[j]; arr[j]=arr[j+1]; arr[j+1]=t; } } } }; //传两个参数,一个待排序的数组,一个方法(判断是升序还是降序)
//升序function(a,b){return a-b}; mySort(arr,function(a,b){return b-a;}); alert(arr); </script>
//默认使用升序 //默认不传参,f的值为undefined
Comparison
Using the encapsulated method, you can flexibly change the sorting method, descending order and ascending order. You only need to change the conditions when defining the f method, and the encapsulated sorting method can be easily called.
SummaryRegarding the encapsulation method, I have gained a good understanding of it in JavaScript.
Continuously repeat,Continuously accumulate~~~
The above is the detailed content of How to implement bubble sort in JavaScript in an encapsulated manner. For more information, please follow other related articles on the PHP Chinese website!