Finalized implementation of nearest neighbors