File tree Expand file tree Collapse file tree 2 files changed +41
-1
lines changed
Expand file tree Collapse file tree 2 files changed +41
-1
lines changed Original file line number Diff line number Diff line change @@ -7,10 +7,50 @@ date: 19-July-2021
77#include < bits/stdc++.h>
88using namespace std ;
99
10- int kSortedArray (int arr[], int num){
10+ // naive solution is sort the given array: O(n*logn)
11+
12+ // this is efficient solution
13+ void kSortedArray (int arr[], int num, int k ){
14+ // create the min heap
15+ priority_queue<int , vector<int >, greater<int > > pq;
16+
17+ // put k elements into min heap
18+ for (int i = 0 ; i<= k; i++){
19+ pq.push (arr[i]);
20+ }
21+
22+ // initialize a varialbe index = 0;
23+ int index = 0 ;
24+
25+ // traverse the remaining element and put them into heap and array
26+
27+ for (int i = k+1 ; i< num; i++){
28+ arr[index++] = pq.top ();
29+ pq.pop ();
30+ pq.push (arr[i]);
31+ }
32+
33+ // put the remaining elements in array to the heap
34+ while (pq.empty () == false ){
35+ arr[index++] = pq.top ();
36+ pq.pop ();
37+ }
1138
1239}
1340
1441int main (){
42+ int num;
43+ cin >> num;
44+ int * arr = new int [num];
45+ for (int i = 0 ; i< num; i++){
46+ cin >> arr[i];
47+ }
48+ int k ;
49+ cin >> k;
50+ kSortedArray (arr, num, k);
51+ // print the array;
52+ for (int i = 0 ; i< num; i++){
53+ cout << arr[i]<<" " ;
54+ }
1555 return 0 ;
1656}
You can’t perform that action at this time.
0 commit comments