<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="./10-2.js"></script>
</body>
</html>
Array.prototype.bubbleSort = function() {
let len = this.length
for (let j=1; j<len; j++) {
for (let i=0; i<len-j; i++) {
// 开始比较,如果第一个数大于第二个数就进行交换,这样大的就到后面去了
if (this[i] > this[i+1]) {
let tempnum = this[i+1]
this[i+1] = this[i]
this[i] = tempnum
}
}
}
}
let arr = [2,9,5,7,1,1,6,3,3,4]
console.log("原来:", arr.toString())
// 原来: 2,9,5,7,1,1,6,3,3,4
arr.bubbleSort()
console.log("排序后:", arr.toString())
// 排序后: 1,1,2,3,3,4,5,6,7,9