插入排序的思路(原理就跟打牌的时候,揭牌并整理牌):
- 从第二个数开始往前比
- 比它大就往后排
- 以此类推进行到最后一个数
排序动画地址:
话不多说,上代码!!!
Array.prototype.insertionSort = function () {
for (let i = 1; i < this.length; i++) {
const temp = this[i];
let j = i;
while (j > 0) {
if (this[j - 1] > temp) {
this[j] = this[j - 1];
} else {
break;
}
j--;
}
this[j] = temp;
}
};
const arr = [5, 4, 3, 2, 1];
arr.insertionSort();
console.log(arr);
时间复杂度:
两个嵌套循环,故插入排序的时间复杂度是O(n^2)
怎么样,是不是很简单,你学会了吗?
如果这篇文章能够帮助到您,希望您不要吝惜点赞👍👍和收藏💖💖,您的支持是我继续努力的动力 💪💪!!!