js 排序算法
阿新 • • 發佈:2019-01-18
mage bubuko blank alt temp pre clas console ima
1、插入排序
原理:
示例代碼:
//插入排序
function insert(a, n) {
let i, j, temp;
for(i = 1; i < n; i++) {
temp = a[i]
for(j = i - 1; j >= 0 && a[j] > temp; j--) {
a[j + 1] = a[j]
}
//找到插入位置
a[j + 1] = temp
}
return a
}
let arr = [8, 4, 7, 1]
console.log(insert(arr, 4))
//希爾排序
2、希爾排序
希爾排序是優化的插入排序,即先分組,再插入排序。
示例代碼:
//希爾排序
function shell(a, n) {
let i, j, temp, stet;
//先分組
for(step = Math.floor(a.length / 2); step >= 1; step = Math.floor(step / 2)) {
//i 從step開始
for(i = step; i < n; i++) {
temp = a[i]
for(j = i - step; j >= 0 && a[j] > temp; j = j - step) {
a[j + step] = a[j]
}
//找到插入位置
a[j + step] = temp
}
}
return a
}
let arr2 = [8, 4, 7, 1]
console.log(shell(arr2, 4))
3、冒泡排序
//冒泡排序
function bubble(a, n) {
let i, j, temp;
for (i=n-1;i>=1;i--) {
for (j=1;j<i;j++) {
if (a[j-1]>a[j]) {
temp = a[j-1]
a[j-1] = a[j]
a[j] = temp
}
}
}
return a
}
let arr3 = [8, 4, 7, 1]
console.log(bubble(arr2, 4))
說明:i指針從後往前。
視頻:https://ke.qq.com/course/350918#term_id=100417287
js 排序算法