Python - Nearest K Sort

The nearest K sort problem requires sorting a list of elements based on their absolute difference from a given value K. Elements with smaller differences appear first in the sorted result.

Understanding the Problem

We need to sort list items by their increasing distance from value K. For each element, we calculate |element - K| and arrange elements based on minimum difference first.

Nearest K Sort Example (K = 10) Original: 10 4 12 15 3 Distance from K=10: |10-10|=0 |4-10|=6 |12-10|=2 |15-10|=5 |3-10|=7 Sorted by distance: 10 dist: 0 12 dist: 2 15 dist: 5 4 dist: 6 3 dist: 7

Algorithm

The approach uses Python's sorted() function with a custom key function ?

  • Step 1 Define a key function that calculates absolute difference between each element and K

  • Step 2 Use sorted() with this key function to sort the list

  • Step 3 Return the sorted list based on nearest distance to K

Implementation

Using Lambda Function

# Define the value K and list of items
K = 10  
numbers = [10, 4, 12, 15, 3, 6, 7, 9]

# Sort by absolute difference from K using lambda
nearest_k_sorted = sorted(numbers, key=lambda x: abs(x - K))

print("Original list:", numbers)
print("K value:", K)
print("Nearest K sorted:", nearest_k_sorted)
Original list: [10, 4, 12, 15, 3, 6, 7, 9]
K value: 10
Nearest K sorted: [10, 9, 12, 7, 6, 15, 4, 3]

Using Custom Function

def distance_from_k(item, k_value):
    """Calculate absolute distance between item and K"""
    return abs(item - k_value)

def nearest_k_sort(numbers, k):
    """Sort list by nearest distance to K"""
    return sorted(numbers, key=lambda x: distance_from_k(x, k))

# Example usage
K = 5
data = [8, 1, 4, 6, 2, 9, 5]
result = nearest_k_sort(data, K)

print(f"Original: {data}")
print(f"K = {K}")
print(f"Nearest K sorted: {result}")

# Show distances for clarity
distances = [(x, abs(x - K)) for x in result]
print("Element (Distance):", distances)
Original: [8, 1, 4, 6, 2, 9, 5]
K = 5
Nearest K sorted: [5, 4, 6, 2, 8, 1, 9]
Element (Distance): [(5, 0), (4, 1), (6, 1), (2, 3), (8, 3), (1, 4), (9, 4)]

Complexity Analysis

Aspect Complexity Reason
Time O(n log n) Sorting operation dominates
Space O(n) New sorted list creation
Key Function O(1) Absolute difference calculation

Practical Applications

This algorithm is useful for finding closest matches, recommendation systems, and data analysis where proximity to a target value matters.

# Finding closest temperatures to room temperature (22°C)
temperatures = [18, 25, 20, 30, 15, 24, 22, 19]
room_temp = 22

closest_temps = sorted(temperatures, key=lambda t: abs(t - room_temp))
print(f"Temperatures closest to {room_temp}°C: {closest_temps}")

# Finding top 3 closest values
top_3_closest = closest_temps[:3]
print(f"Top 3 closest: {top_3_closest}")
Temperatures closest to 22°C: [22, 20, 24, 25, 19, 18, 15, 30]
Top 3 closest: [22, 20, 24]

Conclusion

Nearest K sort efficiently arranges elements by their distance from a target value K using Python's sorted() function with a custom key. This O(n log n) solution is ideal for proximity-based sorting problems.

Updated on: 2026-03-27T15:33:14+05:30

181 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements