The simplest way to implement this is to loop through all elements and store K nearest. (just comparing). Complexity of this is O(n)
which is not so good but no preprocessing is needed. So now really depends on your application. You should use some spatial index to partition area where you search for knn. For some application grid based spatial structure is just fine (just divide your world into fixed block and search only within closes blocks first). This is good when your entities are evenly distributed. Better approach is to use some hierarchical structure like kd-tree... It really all depends on what you need
for more information including pseudocode look in these presentations:
http://www.ulozto.net/xCTidts/dpg06-pdf
http://www.ulozto.net/xoh6TSD/dpg07-pdf