Sort a nearly sorted array (or K sorted arrays)

 Given an array of N elements, where each element is at most k away from its target position, devise and algorithm to sort in O(n logk) time

Method - We can either use insertion sort

code--> 

void insertionsort(int arr[], int size)

{        int i, key, j;

         for(int i=1; i<size; i++)

         {   key=arr[i];

            j=i-1;

            while(j>=0 && arr[j] > key)

            {       arr[i+1]=arr[i];

                     j-=1;

               }

                arr[j+1]=key;

        } 

}


Or we can use Heap Data Structure and learn something new and more optimized, So for this we create 

1. Min Heap of size k+1 with first k+1 elements. This takes O(k) time

2. We then remove min elements one by one from the heap, put them in result array and add a new element to heap from remaining elements.

Code--> 

#include<bits/stdc++.h>

using namespace std;

int kelements(int arr[], int n, int k)

{    priority_queue<int, vector<int>, greater<int,> heapyboi(arr,arr+k+1);

      int index=0 ; 

      for(int i = k+1; i< n ; i++)

                   arr[index++]= heapyboi.top();         //assign top value

                   heapyboi.pop();                                //remove the element    

                   heapyboi.push(arr[i]);                      //push new element inside

while(heapyboi.empty()==false)

    arr[index++] = heapyboi.top();

    heapyboi.pop();

}


Popular posts from this blog

Finding the Subarrays (Hackerearth)

Palindrome Index (Hackerrank)

Sherlock and Array (Hackerrank)