Skip to content
Related Articles
Sort an Array of Points by their distance from a reference Point
• Last Updated : 19 May, 2021

Given an array arr[] containing N points and a reference point P, the task is to sort these points according to their distance from the given point P.

Examples:

Input: arr[] = {{5, 0}, {4, 0}, {3, 0}, {2, 0}, {1, 0}}, P = (0, 0)
Output: (1, 0) (2, 0) (3, 0) (4, 0) (5, 0)
Explanation:
Distance between (0, 0) and (1, 0) = 1
Distance between (0, 0) and (2, 0) = 2
Distance between (0, 0) and (3, 0) = 3
Distance between (0, 0) and (4, 0) = 4
Distance between (0, 0) and (5, 0) = 5

Hence, the sorted array of points will be: {(1, 0) (2, 0) (3, 0) (4, 0) (5, 0)}
Input: arr[] = {{5, 0}, {0, 4}, {0, 3}, {2, 0}, {1, 0}}, P = (0, 0)
Output: (1, 0) (2, 0) (0, 3) (0, 4) (5, 0)
Explanation:
Distance between (0, 0) and (1, 0) = 1
Distance between (0, 0) and (2, 0) = 2
Distance between (0, 0) and (0, 3) = 3
Distance between (0, 0) and (0, 4) = 4
Distance between (0, 0) and (5, 0) = 5
Hence, the sorted array of points will be: {(1, 0) (2, 0) (0, 3) (0, 4) (5, 0)}

Approach: The idea is to store each element at its distance from the given point P in a pair and then sort all the elements of the vector according to the distance stored.

Distance = • Append the distance in an array
• Sort the array of distance and print the points based on the sorted distance.
• Time Complexity: As in the above approach, there is sorting of an array of length N, which takes O(N*logN) time in the worst case. Hence, the Time Complexity will be O(N*log N).
• Auxiliary Space Complexity: As in the above approach, there is extra space used to store the distance and the points as pairs. Hence, the auxiliary space complexity will be O(N).

## Javascript

 

Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up