-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathcode_4.cpp
More file actions
108 lines (94 loc) · 1.93 KB
/
code_4.cpp
File metadata and controls
108 lines (94 loc) · 1.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
//
// code_4.cpp
// Algorithm
//
// Created by Mohd Shoaib Rayeen on 23/11/18.
// Copyright © 2018 Shoaib Rayeen. All rights reserved.
//
#include<iostream>
#include<climits>
using namespace std;
void swap(int *x, int *y) {
int temp = *x;
*x = *y;
*y = temp;
}
class MinHeap {
int *harr;
int heap_size;
public:
MinHeap(int a[], int size);
void MinHeapify(int i);
int parent(int i) {
return (i-1)/2;
}
int left(int i) {
return (2*i + 1);
}
int right(int i) {
return (2*i + 2);
}
int extractMin();
int getMin() {
return harr[0];
}
};
MinHeap::MinHeap(int a[], int size) {
heap_size = size;
harr = a;
int i = (heap_size - 1)/2;
while (i >= 0) {
MinHeapify(i);
i--;
}
}
int MinHeap::extractMin() {
if (heap_size == 0) {
return INT_MAX;
}
int root = harr[0];
if (heap_size > 1) {
harr[0] = harr[heap_size-1];
MinHeapify(0);
}
heap_size--;
return root;
}
void MinHeap::MinHeapify(int i) {
int l = left(i);
int r = right(i);
int smallest = i;
if (l < heap_size && harr[l] < harr[i]) {
smallest = l;
}
if (r < heap_size && harr[r] < harr[smallest]) {
smallest = r;
}
if (smallest != i) {
swap(&harr[i], &harr[smallest]);
MinHeapify(smallest);
}
}
int kthSmallest(int arr[], int n, int k) {
MinHeap obj(arr, n);
for (int i=0; i<k-1; i++) {
obj.extractMin();
}
return obj.getMin();
}
int main() {
int n;
cout << "\nEnter Size\t:\t";
cin >> n;
int *a = new int[n];
cout << "\nEnter Array Elements\n";
for ( int i = 0; i < n; i++ ) {
cin >> a[i];
}
int k;
cout << "Enter K\t:\t";
cin >> k;
cout << "\nKth Smallest Element\t:\t" << kthSmallest( a , n , k ) << endl;
delete[] a;
return 0;
}