About bubbling sorting in JavaScript arrays

Bubble sort: is an algorithm that arranges and displays a series of data in a certain order (from small to large or from large to small)

1. For example: there are [5,4,3,2,1] in the array, and I want it to become [1,2,3,4,5]. The
process is: the
first time 5 is compared with 4, 4 is smaller than him It will be changed to [4,5,3,2,1], and then 5 is compared with 3, and it is found that 3 is also smaller than him, continue to change positions... and so on, until 5 to the end, there is no comparison with it [4, 3,2,1,5].
The second comparison between 4 and the following...[3,2,1,4,5] The
third comparison between 3 and the following...[2,1,3,4,5] The
fourth comparison between 2 and the back...[ 1,2,3,4,5]
This completes the sorting sequence
so that we can draw the rule, the first exchange 4 times, the second exchange 3 times, the third exchange 2 times, and the fourth Exchanged 1 time.

So we use code to show

<script>
	var arr = [5,4,3,2,1]//arr.length是数组中的索引号,从0开始
	for(var i=0;i<=arr.length -1;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;
			}
		}
	}
	console.log(arr)
</script>

What is printed out is exactly the sorted array data we need, which can be randomly shuffled, and the same content will still be obtained in the end. This is bubble sorting, you understand!
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_45054614/article/details/107592147