冒泡排序的思路
数组中有 n 个数,比较每相邻两个数,如果前者大于后者,就把两个数交换位置;这样一来,第一轮就可以选出一个最大的数放在最后面;那么经过 n-1(数组的 length - 1) 轮,就完成了所有数的排序。
然上面的代码已经实现冒泡排序了,但就像注释中提到的,内层 for 循环的次数写成,i < arr.length - 1 ,是不是合适呢? 我们想一下,当第一次,找到最大数,放到最后,那么下一次,遍历的时候,是不是就不能把最后一个数算上了呢?因为他就是最大的了,不会出现,前一个数比后一个数大,要交换位置的情况,所以内层 for 循环的次数,改成 i < arr.length - 1 -j ,才合适,看下面的代码。
// 创建列表类
function ArrayList() {
// 属性
this.array = []
// 方法 将数据可以插入到数组中的方法
ArrayList.prototype.insert = function (item) {
this.array.push(item)
}
// toString
ArrayList.prototype.toString = function () {
return this.array.join("-")
}
// 交换两个位置的数据
ArrayList.prototype.swap = function (m, n) {
var temp = this.array[m]
this.array[m] = this.array[n]
this.array[n] = temp
}
// 实现排序算法C
// 冒泡排序
ArrayList.prototype.bubblesort = function () {
// 1 获取数组的长度
var length = this.array.length
// 第一次: j - length - 1 比较到倒数第二个位置
// 第二次: j - length - 2 比较到倒数第二个位置
// 。。。
for (var j = length - 1; j >= 0 ; j--) {
// 第一次进来 i - 0 比较0 和1 位置的两个数据 如果0 位置大有1位置的数据
// 最后一次进来: i- length - 2 比较length - 2和 length - 1的数据
for (var i = 0; i < j; i++) {
if (this.array[i] > this.array[i + 1]) {
// 交换两个数据
this.swap(i, i + 1)
}
}
}
}
// 选择排序
// 插入【排序
// 希尔排序
}
// 测试类
let list = new ArrayList()
// 插入元素
list.insert(66)
list.insert(88)
list.insert(12)
list.insert(87)
list.insert(100)
list.insert(5)
list.insert(566)
list.insert(23)
alert(list)
// 验证冒泡排序
list.bubblesort()
alert(list)