An example of javascript bubble sorting
- 2021-12-09 08:05:44
- OfStack
Round 2:
Round 3:
Round 4:
Round 5:
Round 6:
Summarize
1. What is bubble sorting
Bubble sorting,
Bubble Sort
By comparing the size of two adjacent elements in turn, in the process of each comparison, the two elements are exchanged to achieve the purpose of order.
If an unordered sequence wants to be sorted from small to large, then the comparison of two elements is achieved by exchanging, and the element on the left is smaller than the element on the right.
If an unordered sequence wants to be sorted from large to small, then the comparison of two elements is achieved by swapping, and the element on the left is larger than the element on the right.
Just like bubble 1 in carbonated drinks, it bubbles from bottom 1 to top.
Step 2 Give an example
If there are 2, 4, 7, 5, 3, 6, 1
Round 1:
i=0;
j (inner layer cycle) cycle 6 times, inner layer cycle to do the work: Two adjacent comparison, the big will eventually put in the back, small in the front, one cycle outer layer cycle control times, inner layer cycle to make judgments
j=0 1 2 3 4 5
2 2 2 2 2 2 2
4 4 4 4 4 4 4
7 7 7 5 5 5 5
5 5 5 7 3 3 3
3 3 3 3 7 6 6
6 6 6 6 6 7 1
1 1 1 1 1 1 7
arr[0] arr[1] arr[2]
arr[1] arr[2] arr[3]
Round 2:
i=1;
j (inner loop) loops 5 times
j=0 1 2 3 4 5
2 2 2 2 2 2
4 4 4 4 4 4
5 5 5 3 3 3
3 3 3 5 5 5
6 6 6 6 6 1
1 1 1 1 1 6
7 7 7 7 7 7
arr[0] arr[1] arr[2]
arr[1] arr[2] arr[3]
Round 3:
i=2;
j (inner layer cycle) cycle 4 times
2 2 2 2 2
4 4 3 3 3
3 3 4 4 4
5 5 5 5 1
1 1 1 1 5
6 6 6 6 6
7 7 7 7 7
Round 4:
i=3;
j (inner loop) loops 3 times
2 2 2 2
3 3 3 3
4 4 4 1
1 1 1 4
5 5 5 5
6 6 6 6
7 7 7 7
Round 5:
i=4;
2 2 2
3 3 1
1 1 3
4 4 4
5 5 5
6 6 6
7 7 7
Round 6:
i=5;
2 1
1 2
3 3
4 4
5 5
6 6
7 7
*/
<script type="text/javascript" >
// Example 1 :
function show(){
var arr=[2,4,7,5,3,6,1];
for(var i=0;i<arr.length-1;i++){
for(var j=0;j<arr.length-1-i;j++){
//1 Compare two adjacent numbers; The big ones come after and the small ones come before
if(arr[j] > arr[j+1] ){
var temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
console.log(arr);
}
// Example 2:
<body>
<input type="text" id="test">
<button type="button" onclick="show()"> Press me </button>
<input type="text" id="sc">
</body>
function show() {
let oT=document.getElementById("test").value;
let sc=document.getElementById("sc");
// console.log(sc);
// console.log(oT);
let arr=oT.split("");
console.log(arr.length);
for (var i = 0; i < arr.length - 1; i++) {
for (var j = 0; j < arr.length - 1 - i; j++) {
//1 Compare two adjacent numbers; The big ones come after and the small ones come before
if (arr[j] > arr[j + 1]) {
var temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
// console.log(arr);
sc.value=arr;
}
</script>
Summarize
This article is here, I hope to give you help, but also hope that you can pay more attention to this site more content!