This repository has been archived by the owner on Jun 20, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 33
/
H_Jay_Patel.c
77 lines (75 loc) · 1.42 KB
/
H_Jay_Patel.c
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
#include <stdio.h>
int l = 0, r = 0;
int median = 0;
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
void maxHeapify(int left[], int i) {
int parent = (i-1)/2;
if(i >= 0 && left[parent] < left[i]) {
swap(&left[parent], &left[i]);
maxHeapify(left, parent);
}
}
void minHeapify(int right[], int i) {
int parent = (i-1)/2;
if(i >= 0 && right[parent] > right[i]) {
swap(&right[parent], &right[i]);
minHeapify(right, parent);
}
}
int findMedian(int x, int left[], int right[], int median) {
if(l > r) {
if(x < median) {
right[r] = left[0];
r++;
minHeapify(right, r-1);
left[0] = x;
swap(&left[0],&left[l-1]);
maxHeapify(left, l-1);
} else {
right[r] = x;
r++;
minHeapify(right, r-1);
}
return (left[0]+right[0])/2;
} else if(l == r) {
if(x < median) {
left[l] = x;
l++;
maxHeapify(left, l-1);
return left[0];
} else {
right[r] = x;
r++;
minHeapify(right, r-1);
return right[0];
}
} else {
if(x < median) {
left[l] = x;
l++;
maxHeapify(left, l-1);
} else {
left[l] = right[0];
l++;
maxHeapify(left, l-1);
right[0] = x;
swap(&right[0],&right[r-1]);
minHeapify(right, r-1);
}
return (left[0]+right[0])/2;
}
}
int main() {
int n;
scanf("%d",&n);
int a[n], left[(n+1)/2], right[(n+1)/2];
for(int i = 0; i < n; i++) {
scanf("%d",&a[i]);
median = findMedian(a[i], left, right, median);
printf("%d ",median);
}
}