The simplest approach is to ignore the nearly sorted property and apply any standard sorting algorithm. However, this doesn’t leverage the fact that elements are already close to their correct positions.
Insertion sort performs well on nearly sorted arrays. Since each element is at most k positions away from its correct place, we can leverage this property to achieve better performance than general sorting.
Since each element is at most k positions away from its correct place, we can use a min heap of size k+1. The smallest element in the first k+1 elements must be the first element in the sorted array. We can continuously extract the minimum and add new elements to maintain this property.
classSolution {
public: vector<int> sortArray(vector<int>& nums, int k) {
priority_queue<int, vector<int>, greater<int>> minHeap;
int n = nums.size();
vector<int> result;
// Add first k+1 elements to heap
for (int i =0; i <= k && i < n; i++) {
minHeap.push(nums[i]);
}
// Process remaining elements
for (int i = k +1; i < n; i++) {
result.push_back(minHeap.top());
minHeap.pop();
minHeap.push(nums[i]);
}
// Extract remaining elements
while (!minHeap.empty()) {
result.push_back(minHeap.top());
minHeap.pop();
}
return result;
}
};
classSolution {
publicint[]sortArray(int[] nums, int k) {
PriorityQueue<Integer> minHeap =new PriorityQueue<>();
int n = nums.length;
int[] result =newint[n];
int resultIndex = 0;
// Add first k+1 elements to heapfor (int i = 0; i <= k && i < n; i++) {
minHeap.add(nums[i]);
}
// Process remaining elementsfor (int i = k + 1; i < n; i++) {
result[resultIndex++]= minHeap.poll();
minHeap.add(nums[i]);
}
// Extract remaining elementswhile (!minHeap.isEmpty()) {
result[resultIndex++]= minHeap.poll();
}
return result;
}
}
classSolution:
defsortArray(self, nums: List[int], k: int) -> List[int]:
import heapq
min_heap = []
n = len(nums)
result = []
# Add first k+1 elements to heapfor i in range(min(k +1, n)):
heapq.heappush(min_heap, nums[i])
# Process remaining elementsfor i in range(k +1, n):
result.append(heapq.heappop(min_heap))
heapq.heappush(min_heap, nums[i])
# Extract remaining elementswhile min_heap:
result.append(heapq.heappop(min_heap))
return result