插入排序思路
插入排序是简单排序中效率最好的一种
插入排序也是学习其他高级排序的基础,比如快速排序,
插入排序思想的核心 局部有序(部分有序)
思路:
- 从 i 等于 1 开始变量,拿到当前数 current,与前面的数进行比较
- 用while进行循环,如果前面的数大于当前的数,那么就进行交换。
- 最好在外部套个循环,直到未排序的数没有了,那么排序就结束。
参考动画:
代码实现
class ArrayList {
array = [];
// 用于插入数字
insert(item) {
this.array.push(item);
}
// 插入排序
insertSort() {
for (let i = 1; i < this.array.length; i++) {
let j = i; // 获取当前的下标值,存起来。
let current = this.array[i]; // 获取当前的数,存起来
// 由于不确定循环次数,所有用while
while (this.array[j - 1] > current && j > 0) {
// 如果当前数的前一个比当前数大,就交换。
this.array[j] = this.array[j - 1];
j--;
}
// 将j位置的数,放到当前位置。
this.array[j] = current;
}
}
}
let list = new ArrayList();
list.insert(12);
list.insert(2);
list.insert(45);
list.insert(123);
list.insert(481);
list.insert(56);
console.log(list.array); // [ 12, 2, 45, 123, 481, 56 ]
// 调用 插入排序
list.insertSort();
console.log(list.array); // [ 2, 12, 45, 56, 123, 481 ]
插入排序的效率
插入排序的比较次数:
- 第一趟时,需要的最多次数是1,第二趟最多次数是2,以此类推,最后一趟是 N-1 次
- 因此插入排序比较的最多次数是:1+2+3+4+....+N-1 = N*(N-1) /2
插入排序的复制次数:
- 第一趟时,需要的最多复制次数是1,第二趟最多次数是2,依次类推,最后一趟是N-1次
- 因此复制最多次数是 :1+2+3+4+....+N-1 = N*(N-1) /2
- 平均次数是 N*(N-1) /4
所以时间复杂度为:O(N²)