K-d tree algorithm