Sort a nearly sorted (or K sorted) array (original) (raw)

Last Updated : 11 Feb, 2025

Try it on GfG Practice redirect icon

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]

Table of Content

[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:

// c++ program to sort k sorted array #include #include #include #include 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 &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 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.