Bubble ranking method in JavaScript
- 2021-07-09 06:39:46
- OfStack
Sort with sort () bubbles:
var arr = [5,39,8,1,2,13,55];
arr = arr.sort(function(a,b){return a-b});
console.log(arr);//1,2,5,8,13,39,55
Do not declare the bubble sort of the third variable:
Layer 1 traverses the number of arrays (how many times to traverse), and the second traversal (how many times to loop)
a = 10; // No. 1 1 Elements
b = 5; // Under 1 Elements
if(a>b){
a = a+b; // a(15) = 10 +5;
b = a-b; // b(10) = 15 - 5;
a = a-b; // a(5) = 15 - 10;
}
var arr = [5,39,8,1,2,13,55];
function jssort(ele){
for (var i=0;i<ele.length;i++){ // How many times do you want to cycle
for (var j=0;j<ele.length-i-1;j++){ // How many times do you want to move
if(ele[j]>ele[j+1]){
ele[j]=ele[j]+ele[j+1]; //a = a+b
ele[j+1]=ele[j]-ele[j+1];//b = a-b
ele[j]=ele[j]-ele[j+1]; //a = a-b
}
}
}
return ele;
}
console.log(jssort(arr));//1,2,5,8,13,39,55
I saw such a colon sort on the Internet today
An array contains element numbers, "110 King Kong 3", "200 King Kong 1", "50 King Kong 2", "30 King Kong 6", "30 King Kong 5" and "30 King Kong 4". How to sort the array according to the later numbers in the string.
Answer: Using sort () sort, use regular expressions in callback functions
arr.sort(function(a,b){return parseInt(a.match(/(\d+)(?= No. )/)[1])-parseInt(b.match(/(\d+)(?= No. )/)[1])});
The match () method retrieves the specified value within a string or finds a match for one or more regular expressions.
This method is similar to indexOf () and lastIndexOf (), but it returns the specified value instead of the position of the string.
a. match (/(\ d +) (? = sign)///Number + zero or 1 times matches the preceding character or subexpression.
Let's take a look at the js bubble sorting example
Example, js implementation of bubble sorting example.
<html>
<head>
<script type="text/javascript">
function sort (arr) {
for (var i = 0;i<arr.length;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;
}
}
}
return arr;
}
var arr=[2,5,3,1,7,8,78,89];
sort(arr);
</script>
</head>
<body>
</body>
</html>