# Sort a nearly sorted array using STL

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. For example, let us consider k is 2, an element at index 7 in the sorted array, can be at indexes 5, 6, 7, 8, 9 in the given array. It may be assumed that k < n.

Input : arr[] = {6, 5, 3, 2, 8, 10, 9} k = 3 Output : arr[] = {2, 3, 5, 6, 8, 9, 10} Input : arr[] = {10, 9, 8, 7, 4, 70, 60, 50} k = 4 Output : arr[] = {4, 7, 8, 9, 10, 50, 60, 70}

A **simple solution **is to sort the array using any standard sorting algorithm. The time complexity of this solution is O(n Log n)

A better solution is to use priority queue (or heap data structure).

1) Build a priority queuepqof first (k+1) elements. 2) Initialize index = 0 (For result array). 3) Do following for elements from k+1 to n-1. a) Pop an item from pq and put it at index, increment index. b) Push arr[i] to pq. 4) While pq is not empty Pop an item from pq and put it at index, increment index.

We have discussed a simple implementation in Sort a nearly sorted (or K sorted) array. In this post, an STL based implementation is done.

`// A STL based C++ program to sort a nearly sorted array. ` `#include <bits/stdc++.h> ` `using` `namespace` `std; ` ` ` `// Given an array of size n, where every element ` `// is k away from its target position, sorts the ` `// array in O(nLogk) time. ` `int` `sortK(` `int` `arr[], ` `int` `n, ` `int` `k) ` `{ ` ` ` `// Insert first k+1 items in a priority queue (or min heap) ` ` ` `//(A O(k) operation) ` ` ` `priority_queue<` `int` `, vector<` `int` `>, greater<` `int` `> > pq(arr, arr + k + 1); ` ` ` ` ` `// i is index for remaining elements in arr[] and index ` ` ` `// is target index of for current minimum element in ` ` ` `// Min Heapm 'hp'. ` ` ` `int` `index = 0; ` ` ` `for` `(` `int` `i = k + 1; i < n; i++) { ` ` ` `arr[index++] = pq.top(); ` ` ` `pq.pop(); ` ` ` `pq.push(arr[i]); ` ` ` `} ` ` ` ` ` `while` `(pq.empty() == ` `false` `) { ` ` ` `arr[index++] = pq.top(); ` ` ` `pq.pop(); ` ` ` `} ` `} ` ` ` `// A utility function to print array elements ` `void` `printArray(` `int` `arr[], ` `int` `size) ` `{ ` ` ` `for` `(` `int` `i = 0; i < size; i++) ` ` ` `cout << arr[i] << ` `" "` `; ` ` ` `cout << endl; ` `} ` ` ` `// Driver program to test above functions ` `int` `main() ` `{ ` ` ` `int` `k = 3; ` ` ` `int` `arr[] = { 2, 6, 3, 12, 56, 8 }; ` ` ` `int` `n = ` `sizeof` `(arr) / ` `sizeof` `(arr[0]); ` ` ` `sortK(arr, n, k); ` ` ` ` ` `cout << ` `"Following is sorted arrayn"` `; ` ` ` `printArray(arr, n); ` ` ` ` ` `return` `0; ` `} ` |

*chevron_right*

*filter_none*

**Output:**

Following is sorted arrayn2 3 6 8 12 56

Time Complexity : O(n Log k)

Auxiliary Space : O(k)

## Recommended Posts:

- Sort a nearly sorted (or K sorted) array
- Sort an array where a subarray of a sorted array is in reverse order
- Sort a Rotated Sorted Array
- Sort an array when two halves are sorted
- Sort an almost sorted array where only two elements are swapped
- Tag Sort (To get both sorted and original)
- Program to sort an array of strings using Selection Sort
- Bucket Sort To Sort an Array with Negative Numbers
- Sort a linked list that is sorted alternating ascending and descending orders?
- Given a sorted array and a number x, find the pair in array whose sum is closest to x
- Check if reversing a sub array make the array sorted
- Why is it faster to process sorted array than an unsorted array ?
- Maximum in an array that can make another array sorted
- Sort an array according to the order defined by another array
- Check whether a given array is a k sorted array or not

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.