js binary search algorithm
js binary search algorithm
js 二分查找算法
二分查找, 前置条件
- 存储在数组中
- 有序排列
理想条件: 数组是递增排列,数组中的元素互不相同;
重排 & 去重
顺序: 递增排列/递减排列;
重复: 数组中存在相同的元素;
"use strict";
/**
*
* @author xgqfrms
* @license MIT
* @copyright xgqfrms
* @created 2020-05-20
* @modified
*
* @description 二分查找 binary-search
* @augments
* @example
* @link
*
*/
const log = console.log;
function binarySearch(data, key, preIndex = 0, debug = false){
let len = data.length;
// 向下取整
let half = Math.floor(len/2);
// 差值
let diffValue = key - data[half];
if(debug) {
// preIndex 保留上次的索引值 indexOf
log(`\npreIndex`, preIndex)
log(`len`, len)
log(`half`, half)
log(`key`, key)
log(`data[half]`, data[half])
// number - undefined == NaN
log(`diffValue`, diffValue)
}
if (diffValue > 0) {
preIndex = preIndex + half + 1;
let right = data.slice(half + 1);
return binarySearch(right, key, preIndex);
} else if (diffValue < 0) {
let left = data.slice(0, half);
return binarySearch(left, key, preIndex);
}else if (diffValue === 0) {
return preIndex + half;
} else {
return -1;
}
}
let v4 = binarySearch([1,3,5,7,9], 9);
log(`v4`, v4)
// 4
let v11 = binarySearch([1,3,5,7,9], 11);
log(`v11`, v11)
// -1
// binarySearch(5, [1,2,3,4,5,6,7,8]);
// // 4
// binarySearch(5, [1,3,5,7,9]);
// // 2
// binarySearch(1, [1,3,5,7,9]);
// // 0
// binarySearch(7, [1,3,5,7,9]);
// // 3
// binarySearch(9, [1,3,5,7,9]);
// // -1
167.
两数之和 II - 输入有序数组
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/
https://leetcode.cn/problems/two-sum-ii-input-array-is-sorted/
BST
function binarySearch(target,arr,start,end) {
if( start > end){
return -1
}
var start = start || 0;
var end = end || arr.length-1;
var mid = parseInt(start + (end-start)/2);
if(target==arr[mid]){
return mid;
}else if(target>arr[mid]){
return binarySearch(target, arr, mid+1, end);
}else{
return binarySearch(target, arr, start, mid-1);
}
return -1;
}
binarySearch(9,[1,2,3,4,5,7,8])
// -1
https://www.jianshu.com/p/eef65b21ace0
Big O
refs
©xgqfrms 2012-2020
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/12927211.html
未经授权禁止转载,违者必究!