Implemented nearest neighbor routine