Input: list of 2d points (x,y) where x and y are integers.
Distance: distance is defined as the Manhattan distance.
ie:
def dist(p1,p2)
return ab
Starting from your initial algortihm, there is an optimization possible:
minDist=inf
bestPoint = null
for p1 in points:
dist = 0
for p2 in points:
dist+=distance(p1,p2)
//This will weed out bad points rather fast
if dist>=minDist then continue(p1)
/*
//Unnecessary because of new line above
minDist = min(dist,minDist)
bestPoint = argmin(p1, bestPoint)
*/
bestPoint = p1
The idea is, to throw away outliers as fast as possible. This can be improved more:
minDist
first, so worse points get thrown away faster)dist
rise fast, possibly triggering the exit condition fasterIf you trade size for speed, you can go another route:
//assumes points are numbered 0..n
dist[]=int[n+1]; //initialized to 0
for (i=0;i
which needs more space for the dist array, but calculates each distance only once. This has the advantage to be better suited to a "get the N best points" sort of problem and for calculation-intensive metrices. I suspect it would bring nothing for the manhattan metric, on an x86 or x64 architecture though: The memory access would heavily dominate the calculation.