using System.Collections.Generic;
public class Point: IComparable<Point>{
public int CompareTo(Point point){
var pointComparer = new PointComparer();
return pointComparer.Compare(this, point);
public override string ToString(){
return "[" + this.x + "," + this.y + "]";
public static double Epsilon = 0.0001;
public static Point P {get;set;}
public static double GetDistanceBetweenTwoPoints(Point point1, Point point2){
var delta1 = point1.x-point2.x;
var delta2 = point1.y-point2.y;
return Math.Sqrt(Math.Pow(delta1,2)+Math.Pow(delta2,2));
public class PointComparer: IComparer<Point>{
public int Compare(Point point1, Point point2){
var d1 = GetDistanceBetweenTwoPoints(P, point1);
var d2 = GetDistanceBetweenTwoPoints(P, point2);
if (Math.Abs(d1 - d2) < Epsilon) res = 0;
else if (d1 > d2) res = 1;
public static Point[] FindKNearestPoints(Point[] points, int k){
var pointComparer = new PointComparer();
var pq = new IntervalHeap<Point>(pointComparer);
for (var i=k; i<points.Length; i++){
var kNearest = new Point[k];
foreach(var point in pq){
public static void Main()
var point1 = new Point{x=8,y=5};
var point2 = new Point{x=2,y=3};
var point3 = new Point{x=-3,y=5};
var point4 = new Point{x=4,y=7};
var point5 = new Point{x=2,y=-2};
var points = new Point[5]{point1,point2,point3,point4,point5};
var kNearest = FindKNearestPoints(points, 3);
foreach(var point in kNearest){
Console.Write(point + " ");