//研究打车软件是如何搜索最近的人的,自己实现了相关的算法
//1.首先建立一个数据结构,初始化中,给所有的人,根据坐标排序
//2.根据坐标去搜索最近的人,我用的是二分法,搜索出最近的人
//3.添加指定位置的人和删除最近位置的人
//4.over不缺东西了
//5.扩展:搜索制定范围的人,很容易写了
var PointArr=function(){
if(this.ctor){
this.ctor.apply(this, arguments);
}
}
PointArr.prototype={
ctor:function(arr){
this.children=[]
if(Object.prototype.toString.call(arr)=="[object Array]"){
this.children=arr.sort(this._sort)
}
},
//按照x和y大小排序
_sort:function(a,b){
if(a.x== b.x){
return a.y> b.y
}else{
return a.x> b.x
}
},
//二分法查找坐标最近的一个位置
indexOf:function(p){
var l=0,r=this.children.length;
while(r-l>1){
var i=(l+r)>>1
var mid=this.children[i]
if(this._sort(p,mid)){
l=i
}else{
r=i
}
}
return r
},
//查找最近的一个人
find:function(p){
var r=this.indexOf(p)
return this.children[r]
},
//插入一个坐标
push:function(p){
var l=this.indexOf(p)
this.children.splice(l,0,p)
},
//删除最近坐标
pop:function(p){
var r=this.indexOf(p)
this.children.splice(r,1)
}
}
//如何给多点坐标排序
var arr=[{
name:"caoke1",
x:21,
y:2
},{
x:21,
y:3
},{
x:22,
y:3
},{
x:1,
y:2
}]
var d=new PointArr(arr)
d.push({
x:21,y:2,z:2
})
//d.pop({
// x:21,y:2,z:2
//})
console.log(d.find({x:21,y:2}))
console.log(d)
//[ { x: 1, y: 2 }, { x: 21, y: 2 }, { x: 21, y: 3 } ]
研究打车软件是如何搜索最近的人的,自己实现了相关的算法 JavaScript版
原文:http://www.cnblogs.com/caoke/p/4998658.html