- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find K Closest Points to the Origin in C++
Suppose we have a set of points. Our task is to find K points which are closest to the origin. Suppose the points are (3, 3), (5, -1) and (-2, 4). Then the closest two (K = 2) points are (3, 3), (-2, 4).
To solve this problem, we will sort the list of points based on their Euclidean distance, after that take the top most K elements from the sorted list. Those are the K nearest points.
Example
#include<iostream> #include<algorithm> using namespace std; class Point{ private: int x, y; public: Point(int x = 0, int y = 0){ this->x = x; this->y = y; } void display(){ cout << "("<<x<<", "<<y<<")"; } friend bool comparePoints(Point &p1, Point &p2); }; bool comparePoints(Point &p1, Point &p2){ float dist1 = (p1.x * p1.x) + (p1.y * p1.y); float dist2 = (p2.x * p2.x) + (p2.y * p2.y); return dist1 < dist2; } void closestKPoints(Point points[], int n, int k){ sort(points, points+n, comparePoints); for(int i = 0; i<k; i++){ points[i].display(); cout << endl; } } int main() { Point points[] = {{3, 3},{5, -1},{-2, 4}}; int n = sizeof(points)/sizeof(points[0]); int k = 2; closestKPoints(points, n, k); }
Output
(3, 3) (-2, 4)
- Related Articles
- Find K Closest Elements in C++
- Find k closest elements to a given value in C++
- C++ Program to Find Closest Pair of Points in an Array
- Find k closest numbers in an unsorted array in C++
- Bitwise AND of sub-array closest to K in C++
- Finding points nearest to origin in JavaScript
- Find the Closest Palindrome in C++
- Closest Pair of Points Problem
- Find closest number in array in C++
- Find the closest and smaller tidy number in C++
- C++ Program to Find k Numbers Closest to Median of S, Where S is a Set of n Numbers
- Program to find three unique elements from list whose sum is closest to k Python
- Find the closest leaf in a Binary Tree in C++
- Find the closest element in Binary Search Tree in C++
- Find the number closest to n and divisible by m in C++

Advertisements