4.1.9.3 插入排序(稳定排序)
- 时间复杂度: О(n2)
- 空间复杂度: O(1)
/**
* 插入排序算法
* @param {Array} arr 需要排序的数组
* @return {Array} 从小到大排序好的数组
*/
function insertSort(arr){
var len = arr.length;
for (var i = 1; i < len; i++) {
var key = arr[i];
var j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
return arr;
}
原文:https://blog.csdn.net/charlene0824/article/details/51387165
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
- wiki: JavaScript
Array.prototype.insertion_sort = function()
{
var i,j;
for(i = 1;i < this.length; i++){
for(j = 0;j<i;j++){
if(this[j]>this[i]){
this.splice(j,0,this[i]);
this.splice(i+1,1);
break;
}
}
}
return this;
};
用法示例:[3,5,2,11,1,2,"abc","zfd","sad","eng"].insertion_sort();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15