JavaScript Program to Find Median in a Stream of Integers (running integers) using Array
Last Updated :
26 Aug, 2024
We have given the integers which are read from the data stream. We need to find the median in a stream of integers also known as running integers using a JavaScript array. We will see various approaches to solve this problem in JavaScript. Below is the example which we help to understand the problem more clearly:
Example:
Input: [ 5, 15, 1, 3, 2, 8, 7, 9, 10, 6, 11, 4 ]
Output: 5 10 5 4 3 4 5 6 7 6.5 7 6.5
Using the Insertion
In this approach, we are inserting the element in the correct position to keep the list stable during the processing of the stream. When the new element is found, we apply the binary search to insert the integer in its proper position. By using the 'findingMedians' function, we are calculating the median by using a sorted array.
Syntax:
function function_name(array , numberValue){
//Binary Search
}
function function_name(array) {
// Median Calculation
}
for(condition) {
let obj = function_name(array);
}
Example: In this example, we will find the median in a stream of integers by using the Insertion approach.
JavaScript
// This function is going to insert the
// number into the sorted array.
function insrtSorts(array, numValue) {
let leftElement = 0;
let rightElement = array.length - 1;
while (
leftElement <= rightElement) {
let middleElement = Math.floor(
(leftElement +
rightElement) / 2);
if (
array[middleElement] ===
numValue) {
array.splice(
middleElement,
0,
numValue);
return;}
else if (
array[middleElement] <
numValue) {
leftElement =
middleElement + 1;}
else {
rightElement =
middleElement - 1;
}}
array.splice(
leftElement,
0,
numValue
);}
// This function is to handle the stream
// of int values and also calculate the
// median in every step
function findingMedians(stream) {
let mediansArray = [];
let sortedNumbersArray = [];
for (
let i = 0;
i < stream.length;
i++) {
let num = stream[i];
insrtSorts(
sortedNumbersArray,
num
);
let median = compMedian(
sortedNumbersArray
);
mediansArray.push(median);
}
return mediansArray;}
// This is the function which we will
// calulcate the median of the sorted
// array
function compMedian(sortedArr) {
let sArrayLen = sortedArr.length;
if (sArrayLen % 2 === 1) {
return sortedArr[
Math.floor(sArrayLen / 2)
];}
else {
let middle1 =
sortedArr[
sArrayLen / 2 - 1
];
let middle2 =
sortedArr[sArrayLen / 2];
return (middle1 + middle2) / 2;
}}
// From here, we are giving the input
let inputArray = [
5, 15, 1, 3, 2, 8, 7, 9, 10, 6, 11,
4,
];
// This is the output which is printed
let outputMedians =
findingMedians(inputArray);
console.log(outputMedians);
Output[
5, 10, 5, 4, 3,
4, 5, 6, 7, 6.5,
7, 6.5
]
Time Complexity: O(N)
Space Complexity: O(N)
Using Sorting
In this approach, we are implementing the basic approach as we are first sorting the list of integers and then sorting the list at each time for computing the median.
Syntax:
function function_name(number) {
// Adding Number to Array
}
function function_name() {
// Sorting array in ascending order
}
for(condition)
// function calls
}
Example: In this example, we are finding the median of stream of integers using Inserting at correct position.
JavaScript
let inputElement = [];
let mediansArray = [];
// Here, we are adding the input
// element in the array
function addingNumInputEleArray(
number) {
inputElement.push(number);
}
// Here, main sorting is done and
// median is found
function sortAndMedian() {
inputElement.sort((a, b) => a - b);
let lengthoFArray =
inputElement.length;
if (lengthoFArray % 2 === 1) {
mediansArray.push(
inputElement[
Math.floor(
lengthoFArray / 2
)]);}
else {
mediansArray.push(
0.5 *
(inputElement[
lengthoFArray / 2] +
inputElement[
lengthoFArray /
2 - 1 ])
);}}
// Input is given
let inputArray = [
5, 15, 1, 3, 2, 8, 7, 9, 10, 6, 11,
4,
];
// Loop to add and find median
// by calling functions
for (let elemt of inputArray) {
addingNumInputEleArray(elemt);
sortAndMedian();
}
// Print result median
console.log(mediansArray);
Output[
5, 10, 5, 4, 3,
4, 5, 6, 7, 6.5,
7, 6.5
]
Time Complexity: O(N log N)
Space Complexity: O(N)
Two-Heap Approach
This method efficiently maintains the median using two heaps: a max-heap for the lower half of the numbers and a min-heap for the upper half.
In this approach, we use two heaps:
- Max-Heap (for the lower half of the numbers) - In JavaScript, a max-heap can be simulated using a min-heap with negative values.
- Min-Heap (for the upper half of the numbers) - This heap stores the larger half of the numbers.
Steps:
- Insert the new number into the appropriate heap.
- Rebalance the heaps if necessary, so that the difference in size between the heaps is at most one.
- Calculate the median:
- If the heaps are of equal size, the median is the average of the tops of the heaps.
- If the max-heap has one more element than the min-heap, the median is the top of the max-heap.
Example:
JavaScript
class MedianFinder {
constructor() {
this.maxHeap = new MaxHeap(); // Simulated max-heap using negative values
this.minHeap = new MinHeap();
}
addNum(num) {
if (this.maxHeap.isEmpty() || num <= this.maxHeap.peek()) {
this.maxHeap.add(-num); // Use negative values for max-heap simulation
} else {
this.minHeap.add(num);
}
// Rebalance heaps if necessary
if (this.maxHeap.size() > this.minHeap.size() + 1) {
this.minHeap.add(-this.maxHeap.poll());
} else if (this.minHeap.size() > this.maxHeap.size()) {
this.maxHeap.add(-this.minHeap.poll());
}
}
findMedian() {
if (this.maxHeap.size() > this.minHeap.size()) {
return -this.maxHeap.peek();
} else {
return (-this.maxHeap.peek() + this.minHeap.peek()) / 2;
}
}
}
// Min-Heap implementation
class MinHeap {
constructor() {
this.heap = [];
}
add(num) {
this.heap.push(num);
this.heapifyUp();
}
poll() {
if (this.isEmpty()) return null;
const root = this.heap[0];
const last = this.heap.pop();
if (!this.isEmpty()) {
this.heap[0] = last;
this.heapifyDown();
}
return root;
}
peek() {
return this.isEmpty() ? null : this.heap[0];
}
size() {
return this.heap.length;
}
isEmpty() {
return this.size() === 0;
}
heapifyUp() {
let index = this.size() - 1;
while (index > 0) {
const parentIndex = Math.floor((index - 1) / 2);
if (this.heap[index] >= this.heap[parentIndex]) break;
[this.heap[index], this.heap[parentIndex]] = [this.heap[parentIndex], this.heap[index]];
index = parentIndex;
}
}
heapifyDown() {
let index = 0;
while (index < this.size()) {
const leftIndex = 2 * index + 1;
const rightIndex = 2 * index + 2;
let smallest = index;
if (leftIndex < this.size() && this.heap[leftIndex] < this.heap[smallest]) smallest = leftIndex;
if (rightIndex < this.size() && this.heap[rightIndex] < this.heap[smallest]) smallest = rightIndex;
if (smallest === index) break;
[this.heap[index], this.heap[smallest]] = [this.heap[smallest], this.heap[index]];
index = smallest;
}
}
}
// Max-Heap implementation (simulated with negative values)
class MaxHeap extends MinHeap {
heapifyUp() {
let index = this.size() - 1;
while (index > 0) {
const parentIndex = Math.floor((index - 1) / 2);
if (this.heap[index] <= this.heap[parentIndex]) break;
[this.heap[index], this.heap[parentIndex]] = [this.heap[parentIndex], this.heap[index]];
index = parentIndex;
}
}
heapifyDown() {
let index = 0;
while (index < this.size()) {
const leftIndex = 2 * index + 1;
const rightIndex = 2 * index + 2;
let largest = index;
if (leftIndex < this.size() && this.heap[leftIndex] > this.heap[largest]) largest = leftIndex;
if (rightIndex < this.size() && this.heap[rightIndex] > this.heap[largest]) largest = rightIndex;
if (largest === index) break;
[this.heap[index], this.heap[largest]] = [this.heap[largest], this.heap[index]];
index = largest;
}
}
}
const medianFinder = new MedianFinder();
const inputArray = [5, 15, 1, 3, 2, 8, 7, 9, 10, 6, 11, 4 ];
const mediansArray = [];
for (const num of inputArray) {
medianFinder.addNum(num);
mediansArray.push(medianFinder.findMedian());
}
console.log(mediansArray);
Output[
5, 10, 1, 2, 1,
2, 1, 4, 1, 3.5,
1, 2.5
]
Similar Reads
Median of Two Sorted Arrays of Different Sizes using JavaScript Given two arrays, our goal is to find the median of two sorted arrays of different sizes by merging both of them. The median is the middle value of the array after dividing it into two halves. Example: Input: Arr1: [1,4,5], Arr2: [2,8,7,3]Output: Median = 4Explanation: The merged and sorted array is
4 min read
Median of 2 Sorted Arrays of Equal Size using JavaScript The median is the middle element of the array. If several elements are odd then the middle element is the median and if several elements are even then the average of the two middle values is the median after arranging the array in sorted order. Below are the approaches to find the median of 2 sorted
3 min read
Javascript Program to Find median in row wise sorted matrix We are given a row-wise sorted matrix of size r*c, we need to find the median of the matrix given. It is assumed that r*c is always odd.Examples: Input : 1 3 5 2 6 9 3 6 9Output : Median is 5If we put all the values in a sorted array A[] = 1 2 3 3 5 6 6 9 9)Input: 1 3 4 2 5 6 7 8 9Output: Median is
4 min read
How to Perform Parallel Processing on Arrays in Java Using Streams? In Java, parallel processing helps to increase overall performance. Arrays may be processed in parallel in Java by using Streams API. When working with big datasets or computationally demanding tasks, this is very helpful. In this article, we will learn how to perform parallel processing on arrays i
2 min read
Java Program to Sort the Elements of an Array in Descending Order Here, we will sort the array in descending order to arrange elements from largest to smallest. The simple solution is to use Collections.reverseOrder() method. Another way is sorting in ascending order and reversing.1. Using Collections.reverseOrder()In this example, we will use Collections.reverseO
2 min read
How to get median of an array of numbers in JavaScript ? In this article, we will see how to find the median of an array using JavaScript. A median is a middle value in a given set of numbers or data. Examples: Input arr1 : [1 4 7 9]Output : 5.5Explanation : The median of the two sorted array is the middle elements which is 5 if the arrayLength =arr1.leng
3 min read
Javascript Program to Find the subarray with least average Given an array arr[] of size n and integer k such that k <= n.Examples : Input: arr[] = {3, 7, 90, 20, 10, 50, 40}, k = 3Output: Subarray between indexes 3 and 5The subarray {20, 10, 50} has the least average among all subarrays of size 3.Input: arr[] = {3, 7, 5, 20, -10, 0, 12}, k = 2Output: Sub
3 min read
PHP Program To Find Mean and Median of an Unsorted Array Given an unsorted array, the task is to find the mean (average) and median of the array in PHP. we will see the approach and code example to solve this problem. ApproachTo find the mean of an array, we need to sum up all the elements in the array and then divide the sum by the total number of elemen
2 min read
How to Find the Median of a Sorted Array in C++? In C++, the median of a sorted array is the middle element if the array size is odd, or the average of the two middle elements if the array size is even. In this article, we will learn how to find the median of a sorted array in C++. Example Input: myArray: {1, 2, 3, 4, 5} Output: Median of the Arra
2 min read
C# Program to Print Only Those Numbers Whose Value is Less Than Average of all Elements in an Integer Array using LINQ Language-Integrated Query (LINQ) is a uniform query syntax in C# to retrieve data from different sources. It eliminates the mismatch between programming languages and databases and also provides a single querying interface for different types of data sources. In this article, we will learn how to pr
2 min read