[JavaScript case]-Use JS to realize bubble sorting in sorting algorithm
Before we talked about using Python to implement bubble sorting in sorting algorithms, today we will take a look at how to use JS to implement bubble sorting in sorting algorithms.
So what is the sorting algorithm?
The concept of sorting:
- Rearrange the data according to the specified rules, in positive order (from small to large) or in reverse order
Bubble sort formula:
- Sort by N numbers, each pair is smaller and higher, the outer layer loops N-1, the inner layer loops Ni-1
achieve:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
window.onload = function () {
var arr = [18, 9, 21, 47, 15, 23, 11];
// 外层循环控制的是比较的轮数
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>
</body>
</html>