17. Sort by Absolute Difference
β GFG solution to the Sort by Absolute Difference problem: rearrange array elements based on their absolute difference from a target value using stable sorting technique. π
π§© Problem Description
π Examples
Example 1
Input: x = 7, arr[] = [10, 5, 3, 9, 2]
Output: [5, 9, 10, 3, 2]
Explanation: Sorting the numbers according to the absolute difference with 7:
- |5-7| = 2 (closest)
- |9-7| = 2 (same distance, maintain original order)
- |10-7| = 3
- |3-7| = 4
- |2-7| = 5 (farthest)Example 2
π Constraints
β
My Approach
Stable Sort with Lambda Comparator
π Time and Auxiliary Space Complexity
π§βπ» Code (C++)
β Code (Java)
π Code (Python)
π§ Contribution and Support
πVisitor Count
Last updated