KNN function code