Finished the nearest neighbor function