Ex 5.2: Modified nearest neighbor function.