Sort a nearly sorted (or K sorted) array
www.geeksforgeeks.org/nearly-sort…
Given an array of N elements, where each element is at most K away from its target position, devise an algorithm that sorts in O(N log K) time.
- Create a Min Heap of size K+1 with the first K+1 elements. We are creating a heap of size K as the element can be at most K distance from its index in a sorted array.
- One by one remove the min element from the heap, put it in the result array, and add a new element to the heap from the remaining elements.