代码(搜索无果返回null):
Object.defineProperty(Array.prototype, 'binary', {
writable: true,
enumerable: false,
configurable: true,
value(callback, low, high){
if (low === undefined) low = 0;
if (high === undefined) high = this.length;
console.log({low, high});
var mid = ~~((low + high) / 2);
var item = this[mid];
var result = callback(item, mid);
if (result === 0) {
return item;
} else if (result < 0) {
if (mid === low) return null;
return this.binary(callback, mid, high);
} else if (result > 0) {
if (mid === high) return null;
return this.binary(callback, low, mid);
}
}
});
一维数组示例:
var len = 1000000;
var arr = [];
for (var i = 0; i < len; i++){
var id = ~~(Math.random() * len)
arr[i] = {
id: id,
text: `第${id}个text`
};
}
arr.sort((a, b) => {return a.id - b.id});
// 取出 id 为 408798 的项
var result = arr.binary((item, index) => {
return item.id - 408798;
});
二维数组示例:
var len = 1000000;
var arr = [];
for (var i = 0; i < len; i++){
var x = ~~(Math.random() * len);
var y = ~~(Math.random() * len);
arr[i] = {
coord: [x, y],
text: `坐标为${x},${y}的text`
};
}
arr.sort((a, b) => {
if (a.coord[0] === b.coord[0]) {
return a.coord[1] - b.coord[1];
} else {
return a.coord[0] - b.coord[0];
}
});
// 取出 coord 为 [4041, 9651] 的项
var result = arr.binary((item, index) => {
if (item.coord[0] !== 4041) return item.coord[0] - 4041;
else return item.coord[1] - 9651;
});