forked from wahyuhjr/OpenEmailGenerator
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Median of data stream of integer.cpp
81 lines (62 loc) · 1.6 KB
/
Median of data stream of integer.cpp
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
// This code is contributed by Rishabh Verma
#include <bits/stdc++.h>
using namespace std;
// Function to find position to insert current element of
// stream using binary search
int binarySearch(int arr[], int item, int low, int high)
{
if (low >= high) {
return (item > arr[low]) ? (low + 1) : low;
}
int mid = (low + high) / 2;
if (item == arr[mid])
return mid + 1;
if (item > arr[mid])
return binarySearch(arr, item, mid + 1, high);
return binarySearch(arr, item, low, mid - 1);
}
// Function to print median of stream of integers
void printMedian(int arr[], int n)
{
int i, j, pos, num;
int count = 1;
cout << "Median after reading 1"
<< " element is " << arr[0] << "\n";
for (i = 1; i < n; i++) {
float median;
j = i - 1;
num = arr[i];
// find position to insert current element in sorted
// part of array
pos = binarySearch(arr, num, 0, j);
// move elements to right to create space to insert
// the current element
while (j >= pos) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = num;
// increment count of sorted elements in array
count++;
// if odd number of integers are read from stream
// then middle element in sorted order is median
// else average of middle elements is median
if (count % 2 != 0) {
median = arr[count / 2];
}
else {
median = (arr[(count / 2) - 1] + arr[count / 2])
/ 2;
}
cout << "Median after reading " << i + 1
<< " elements is " << median << "\n";
}
}
// Driver Code
int main()
{
int arr[] = { 5, 15, 1, 3, 2, 8, 7, 9, 10, 6, 11, 4 };
int n = sizeof(arr) / sizeof(arr[0]);
printMedian(arr, n);
return 0;
}