<! DOCTYPE html>
<meta charset= "Utf-8" >
<meta http-equiv= "x-ua-compatible" content= "ie=edge,chrome=1" >
<meta name= "viewport" content= "width=device-width; initial-scale=1.0; minimum-scale=1.0; maximum-scale=2.0 "/>
<title> bubble Sort-leaf making </title>
<meta name= "description" content= "bubble sort"/>
<meta name= "keywords" content= "leaves"/>
<style>
body{width:500px;margin:50px Auto;}
span{display:inline-block;margin-bottom:20px;}
</style>
<body>
Original array: <span id= "Beforary" >100,12,3,4,5,6,2</span><br/>
Array after sorting: <span id= "Afterary" ></span>
</body>
<script type= "Text/javascript" >
/* Method One:
var beforetxt = document.getElementById ("Beforary"). InnerHTML;
var aftertxt = document.getElementById ("Afterary");
var myarytxt = Beforetxt.split (",");
var copeary = Myarytxt.concat ();
var newary = Copeary.sort (function (A, b) {
return a-B;
});
aftertxt.innerhtml = newary;
Note: Sorting in this place is not a sort of number, but rather a sort of string
The method is simple and does not explain too much;
*/
/* Method Two:
* Thought
* Each round will be the largest in the back, so the number of n comparison n-1 wheel (that is, the maximum number of n-1 placed in the back) can be a-I starting from 0;
* How many times per round, do not compare with yourself, up to n-1 times;
*i=0, n-1-0 (--0 will be put to the back of the removal)
*i=1, N-1-1
*i=2, N-1-2
* ...
*i=i, N-1-i
*/
var beforetxt = document.getElementById ("Beforary"). InnerHTML; Gets the string number that you want to sort;
var aftertxt = document.getElementById ("Afterary"); Get the position where you want to place the number in the row;
var myarytxt = Beforetxt.split (","); The obtained string is split;
var myAry1 = []; Declare an empty array (prepare for the array you have placed)
for (Var i=0;i<myarytxt.length;i++) {//Use loops to get the split separately;
var myary = number (myarytxt[i]); Converts each character number obtained into a pure number;
Myary1.push (myary); Storing or converting numbers as array elements;
}
var copeary = Myary1.concat (); Copy an array;
function sortary (ary) {//Specify functions
for (Var i=0;i<ary.length-1;i++) {//i is the number of control wheels
for (Var j=0;j<ary.length-1-i;j++) {//j controls how many times each round is compared;
if (Ary[j]>ary[j+1]) {//If the current number is less than the next, the position is swapped;
var temp = null;
temp = Ary[j];
ARY[J] = ary[j+1];
ARY[J+1] = temp;
}
}
}
return ary; Returns the sorted array;
}
var newary = sortary (copeary); Execute function
aftertxt.innerhtml = newary; The resulting array is placed in the specified position;
</script>
</body>
JS two ways to implement sorting