Sort a nearly sorted (or K sorted) array
Last Updated :
11 Feb, 2025
Given an array arr[] and a number k . The array is sorted in a way that every element is at max k distance away from it sorted position. It means if we completely sort the array, then the index of the element can go from i – k to i + k where i is index in the given array. Our task is to completely sort the array.
Examples:
Input: arr= [6, 5, 3, 2, 8, 10, 9], k = 3
Output: [2, 3, 5, 6, 8, 9, 10]
Input: arr[]= [1, 4, 5, 2, 3, 6, 7, 8, 9, 10], k = 2
Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[Naive Approach] By sorting – O(n*log n) Time and O(1) Space
We can simply use any sorting algorithm of O(n*log n) time complexity to achieve sorted array.
[Expected Approach] Using Heap – O(n*log k) Time and O(k) Space
The main idea is to sort the array efficiently from left to right by considering elements from the right side. For each position i, we find the minimum element in the range [i, i + k] with help of min-heap. we don’t need to check numbers from left side as they are already at their correct positions.
Step by Step implementation:
- Push the first k elements of the array into the min-heap. These elements form the initial search range for sorting the first few indices.
- Iterate through the remaining elements of the array (from index k to n-1). For each element:
- Push it into the min-heap.
- The heap now contains k + 1 elements, so remove the smallest element (top of the heap) and place it at its correct position in the array (arr[i-k]).
- After processing all elements in the array, the heap still contains the last k elements. Extract these elements one by one and place them in the remaining positions of the array.
C++
// c++ program to sort k sorted array
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
// function to sorts a nearly sorted array
// where every element is at most
// k positions away from its target position.
void nearlySorted(vector<int> &arr, int k) {
// length of array
int n = arr.size();
// creating a min heap
priority_queue<int, vector<int>, greater<int>> pq;
// pushing first k elements in pq
for (int i = 0; i < k; i++)
pq.push(arr[i]);
int i;
for (i = k; i < n; i++) {
pq.push(arr[i]);
// size becomes k+1 so pop it
// and add minimum element in (i-k) index
arr[i - k] = pq.top();
pq.pop();
}
// puting remaining elements in array
while (!pq.empty()) {
arr[i - k] = pq.top();
pq.pop();
i++;
}
}
int main() {
vector<int> arr = {6, 5, 3, 2, 8, 10, 9};
int k = 3;
nearlySorted(arr, k);
for (int x : arr)
cout << x << ' ';
return 0;
}
Java
// Java program to sort a nearly sorted array
import java.util.*;
class GfG {
// Function to sort a nearly sorted array
// where every element is at most
// k positions away from its target position.
static void nearlySorted(int[] arr, int k) {
// Length of array
int n = arr.length;
// Creating a min heap
PriorityQueue<Integer> pq = new PriorityQueue<>();
// Pushing first k elements in pq
for (int i = 0; i < k; i++)
pq.add(arr[i]);
int i;
for (i = k; i < n; i++) {
pq.add(arr[i]);
// Size becomes k+1 so pop it
// and add minimum element in (i-k) index
arr[i - k] = pq.poll();
}
// Putting remaining elements in array
while (!pq.isEmpty()) {
arr[i - k] = pq.poll();
i++;
}
}
public static void main(String[] args) {
int k = 3;
int[] arr = {6, 5, 3, 2, 8, 10, 9};
nearlySorted(arr, k);
for (int x : arr) {
System.out.print(x + " ");
}
}
}
Python
# A Python program to sort a
# nearly sorted array.
import heapq
# Function to sort a nearly sorted array
# where every element is at most
# k positions away from its target position.
def nearlySorted(arr, k):
# Length of array
n = len(arr)
# Creating a min heap
pq = []
# Pushing first k elements in pq
for i in range(k):
heapq.heappush(pq, arr[i])
i = k
index = 0
while i < n:
heapq.heappush(pq, arr[i])
# Size becomes k+1 so pop it
# and add minimum element in (index) position
arr[index] = heapq.heappop(pq)
i += 1
index += 1
# Putting remaining elements in array
while pq:
arr[index] = heapq.heappop(pq)
index += 1
if __name__ == "__main__":
k = 3
arr = [6, 5, 3, 2, 8, 10, 9]
nearlySorted(arr, k)
print(" ".join(map(str, arr)))
JavaScript
// javascript program to sort k sorted array
class MinHeap {
constructor() {
this.heap = [];
}
push(val) {
this.heap.push(val);
this.heapifyUp();
}
pop() {
if (this.heap.length === 1) return this.heap.pop();
const min = this.heap[0];
this.heap[0] = this.heap.pop();
this.heapifyDown();
return min;
}
heapifyUp() {
let index = this.heap.length - 1;
while (index > 0) {
let parentIndex = Math.floor((index - 1) / 2);
if (this.heap[parentIndex] <= this.heap[index]) break;
[this.heap[parentIndex], this.heap[index]] = [this.heap[index], this.heap[parentIndex]];
index = parentIndex;
}
}
heapifyDown() {
let index = 0;
while (true) {
let left = 2 * index + 1;
let right = 2 * index + 2;
let smallest = index;
if (left < this.heap.length && this.heap[left] < this.heap[smallest]) {
smallest = left;
}
if (right < this.heap.length && this.heap[right] < this.heap[smallest]) {
smallest = right;
}
if (smallest === index) break;
[this.heap[index], this.heap[smallest]] = [this.heap[smallest], this.heap[index]];
index = smallest;
}
}
isEmpty() {
return this.heap.length === 0;
}
}
// Function to sort a nearly sorted array
// where every element is at most k positions away from its target position.
function nearlySorted(arr, k) {
let n = arr.length;
let pq = new MinHeap();
// Pushing first k elements in pq
for (let i = 0; i < k; i++) {
pq.push(arr[i]);
}
let index = 0;
for (let i = k; i < n; i++) {
pq.push(arr[i]);
// Size becomes k+1 so pop it
// and add minimum element in (index) position
arr[index] = pq.pop();
index++;
}
// Putting remaining elements in array
while (!pq.isEmpty()) {
arr[index] = pq.pop();
index++;
}
}
// Driver code
let arr = [6, 5, 3, 2, 8, 10, 9];
let k = 3;
nearlySorted(arr, k);
console.log(arr.join(" "));
Note: We can also use a Balanced Binary Search Tree instead of a Heap to store k+1 elements. The insert and delete operations on Balanced BST also take O(log k) time. So Balanced BST-based method will also take O(n log k) time, but the Heap based method seems to be more efficient as the minimum element will always be at the root. Also, Heap doesn’t need extra space for left and right pointers.
Similar Reads
Sorting Algorithms
A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to Sorting Techniques â Data Structure and Algorithm Tutorials
Sorting refers to rearrangement of a given array or list of elements according to a comparison operator on the elements. The comparison operator is used to decide the new order of elements in the respective data structure. Why Sorting Algorithms are ImportantThe sorting algorithm is important in Com
3 min read
Most Common Sorting Algorithms
Selection Sort
Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted. First we find the smallest element a
8 min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high. We sort the array using multiple passes. After the fi
8 min read
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. How do
14 min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
13 min read
Heap Sort - Data Structures and Algorithms Tutorials
Heap sort is a comparison-based sorting technique based on Binary Heap Data Structure. It can be seen as an optimization over selection sort where we first find the max (or min) element and swap it with the last (or first). We repeat the same process for the remaining elements. In Heap Sort, we use
14 min read
Counting Sort - Data Structures and Algorithms Tutorials
Counting Sort is a non-comparison-based sorting algorithm. It is particularly efficient when the range of input values is small compared to the number of elements to be sorted. The basic idea behind Counting Sort is to count the frequency of each distinct element in the input array and use that info
9 min read