Skip to content

Commit bc2bfa5

Browse files
Merge pull request #381 from ys13579/master
K largest elements in unsorted array
2 parents 855dfbe + 1c48a15 commit bc2bfa5

File tree

1 file changed

+116
-0
lines changed

1 file changed

+116
-0
lines changed
+116
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
#include <iostream>
2+
using namespace std;
3+
4+
// Swap function to interchange
5+
int swap(int& x, int& y)
6+
{
7+
int temp = x;
8+
x = y;
9+
y = temp;
10+
}
11+
12+
// Min Heap Class
13+
class MinHeap {
14+
15+
int size;
16+
int* arr;
17+
18+
public:
19+
// Constructor to initialize the size and arr
20+
MinHeap(int size, int input[]);
21+
22+
// heap property for i.
23+
void heapify(int i);
24+
25+
// Build the min heap
26+
void buildHeap();
27+
};
28+
29+
30+
MinHeap::MinHeap(int size, int input[])
31+
{
32+
// Initializing arr and size
33+
this->size = size;
34+
this->arr = input;
35+
36+
// Building the Min Heap
37+
buildHeap();
38+
}
39+
40+
void MinHeap::heapify(int i)
41+
{
42+
//Case 1:Leaf Node
43+
if (i >= size / 2)
44+
return;
45+
46+
// variable to store the smallest element
47+
int smallest;
48+
49+
// Index of left node
50+
int left = 2 * i + 1;
51+
52+
// Index of right node
53+
int right = 2 * i + 2;
54+
55+
56+
// Compare left node with current i node
57+
smallest = arr[left] < arr[i] ? left : i;
58+
59+
// Compare right node with smallest node
60+
if (right < size)
61+
smallest = arr[right] < arr[smallest]
62+
? right : smallest;
63+
64+
// If Node i violates the min heap property, swap current node i with smallest to fix the min-heap property and recursively call heapify for node smallest.
65+
if (smallest != i) {
66+
swap(arr[i], arr[smallest]);
67+
heapify(smallest);
68+
}
69+
}
70+
71+
// Build Min Heap
72+
void MinHeap::buildHeap()
73+
{
74+
// Calling Heapify for all non leaf nodes
75+
for (int i = size / 2 - 1; i >= 0; i--) {
76+
heapify(i);
77+
}
78+
}
79+
80+
void MaxKelements(int arr[],int size,int k){
81+
// Creating Min Heap for first K elements
82+
MinHeap* m = new MinHeap(k, arr);
83+
84+
// Loop For each element in array after the kth element
85+
for (int i = k; i < size; i++) {
86+
87+
if (arr[0] > arr[i])
88+
continue;
89+
else {
90+
arr[0] = arr[i];
91+
m->heapify(0);
92+
}
93+
}
94+
//Iterate and print K large elements
95+
for (int i = 0; i < k; i++) {
96+
cout << arr[i] << " ";
97+
}
98+
}
99+
100+
101+
int main()
102+
{
103+
104+
int arr[] = { 111, 93, 11, 152, 5, 42,
105+
435, 188, 96, 150, 455 };
106+
107+
int size = sizeof(arr) / sizeof(arr[0]);
108+
109+
// Size of Min Heap
110+
int k = 3;
111+
112+
MaxKelements(arr,size,k);
113+
114+
return 0;
115+
}
116+

0 commit comments

Comments
 (0)