1
0
mirror of https://github.com/142vip/408CSFamily.git synced 2026-04-10 05:59:18 +08:00
Files
408CSFamily/code/ds/BinaryInsertSort.js
最近在学桌球 6a1567cd2e feat: 更新文档
2023-08-30 17:04:20 +08:00

45 lines
988 B
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 折半插入排序【JavaScript版本】
*/
function binaryInsertSort(arr, len) {
// 数组长度校验【非必须】
len = arr.length === len
? len
: arr.length
for (let i = 1; i < len; i++) {
const temp = arr[i]
let lowIndex = 0; let highIndex = i - 1
while (lowIndex <= highIndex) {
// 注意:取整,javascript这里取整会出现空指针
const mid = parseInt((lowIndex + highIndex) / 2)
if (arr[mid] <= temp) {
// 右侧
lowIndex = mid + 1
} else {
// 左侧
highIndex = mid - 1
}
}
// 元素后移
for (let j = i - 1; j > highIndex; --j) {
arr[j + 1] = arr[j]
}
arr[highIndex + 1] = temp
}
// 返回经过折半插入排序处理的有序数组
return arr
}
const dealArr = [5, 2, 7, 3, 18, 8, 12, 1]
console.log('插入排序前:', dealArr)
const sortResult = binaryInsertSort(dealArr, 7)
console.log('插入排序后:', sortResult)