 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python - Nearest K Sort
The given problem statement is required to find the nearest of K and sort them as per the value of K using Python. So we will use basic Python to solve this problem.
Understanding the Problem
The problem at hand is to sort the given items of the list as per the increasing difference from the value of K. And K is the given value which will be used to calculate the difference from each item and arrange the items based on the minimum difference. Let's understand this problem with an example:
 
 So we can see here that the difference is increasing. And we have arranged the item as per the increasing difference of the item with the value of K.
Logic for The Above Problem
To solve the given problem we will use the abs function which will be used to calculate the absolute difference between K and the items of the list. So by using this difference we will sort the given list which is the required result.
Algorithm
- Step 1 Define a function called item_distance and pass the items of the list one by one to get the difference between K and item. 
- Step 2 After getting the difference we will initialize the value of K and the list as items. 
- Step 3 So with the help of the sorted method we will sort the given items of the list based on the item_distance. 
Example
# Define the function to find the distance def item_distance(item): return abs(item - K) #Initialize the value of K K = 10 #The list of items items = [10, 4, 12, 15, 3, 6, 7, 9] # Sort the input list as per the distance from K sorted_items = sorted(items, key=item_distance) print(sorted_items)
Output
[10, 9, 12, 7, 6, 15, 4, 3]
Complexity
The time taken by the code for sorting the given input list based on the value of K is O(n log n), here n is the size of the input list. As we have used abs function which is a built-in function in Python to calculate the absolute difference between K and list items. And used the sorted function which requires O(n log n) time to sort the elements.
Conclusion
We have successfully created the code for the given problem of sorting the items based on the difference between items and K. As we have used two built-in functions abs and sorted to minimize the time of the execution. This algorithm is efficient for sorting these kinds of problems.
