//Driver Code Starts
using System;
using System.Collections.Generic;
class GFG {
//Driver Code Ends
// Function to calculate squared distance from the origin
static int squaredDis(int[,] point, int idx)
{
return point[idx, 0] * point[idx, 0] + point[idx, 1] * point[idx, 1];
}
static int partition(int[,] points, int left, int right)
{
// Last element is chosen as a pivot.
int pivotX = points[right, 0];
int pivotY = points[right, 1];
int i = left;
for (int j = left; j < right; j++)
{
int distJ = points[j, 0] * points[j, 0] + points[j, 1] * points[j, 1];
int distPivot = pivotX * pivotX + pivotY * pivotY;
if (distJ <= distPivot)
{
// Swap points[i] and points[j]
int tempX = points[i, 0], tempY = points[i, 1];
points[i, 0] = points[j, 0];
points[i, 1] = points[j, 1];
points[j, 0] = tempX;
points[j, 1] = tempY;
i++;
}
}
// Swap pivot to its correct position
int tempPX = points[i, 0], tempPY = points[i, 1];
points[i, 0] = points[right, 0];
points[i, 1] = points[right, 1];
points[right, 0] = tempPX;
points[right, 1] = tempPY;
return i;
}
static void quickSelect(int[,] points, int left, int right, int k)
{
if (left <= right)
{
int pivotIdx = partition(points, left, right);
// Count of all elements in the left part
int leftCnt = pivotIdx - left + 1;
if (leftCnt == k)
return;
// Search in the left subarray
if (leftCnt > k)
quickSelect(points, left, pivotIdx - 1, k);
// Reduce the k by number of elements already covered
// and search in the right subarray
else
quickSelect(points, pivotIdx + 1, right, k - leftCnt);
}
}
// Function to return k closest points to the origin
static List<List<int>> kClosest(int[,] points, int k)
{
quickSelect(points, 0, points.GetLength(0) - 1, k);
List<List<int>> res = new List<List<int>>();
for (int i = 0; i < k; i++)
{
List<int> temp = new List<int> { points[i, 0], points[i, 1] };
res.Add(temp);
}
return res;
}
//Driver Code Starts
static void Main()
{
int[,] points = new int[,]
{
{ 1, 3 },
{ -2, 2 },
{ 5, 8 },
{ 0, 1 }
};
int k = 2;
List<List<int>> res = kClosest(points, k);
foreach (List<int> point in res)
{
Console.WriteLine(point[0] + ", " + point[1]);
}
}
}
//Driver Code Ends