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
JavaScript Program to Find the Missing Number in a Given Integer Array of 1 to 100
In this article, we are going to find the missing number in a given integer array of 1 to 100 in JavaScript, Given an array [] of size 100 with integers in the range of [1, 100], There are no duplicate values in the array and no larger value than the size of the array. The task is to print that whic
5 min read
JavaScript Program for Insertion Sort
What is Insertion Sort Algorithm?Insertion sorting is one of the sorting techniques that is based on iterating the array and finding the right position for every element. It compares the current element to the predecessors, if the element is small compare it with the elements before. Move ahead to a
4 min read
JavaScript Program for Quick Sort
What is Quick Sort Algorithm?Quick sort is one of the sorting algorithms that works on the idea of divide and conquer. It takes an element as a pivot and partitions the given array around that pivot by placing it in the correct position in the sorted array. The pivot element can be selected in the f
4 min read
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
Javascript Program for Mean of range in array
Given an array of n integers. You are given q queries. Write a program to print the floor value of mean in range l to r for each query in a new line.Examples : Input : arr[] = {1, 2, 3, 4, 5} q = 3 0 2 1 3 0 4 Output : 2 3 3 Here for 0 to 2 (1 + 2 + 3) / 3 = 2 Input : arr[] = {6, 7, 8, 10} q = 2 0 3
3 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
Java Program to Convert Integer List to Integer Array
There are many ways to convert integer List to ArrayList where in this article we will be discussing out 2 approaches as below: Using concept od streams in Java8Using Apache Commons LangUsing Guava Library Method 1: Using concept od streams in Java8 So, first, we will get to know about how to conver
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 for Menu Driven Sorting of Array
In Java, sorting an array consists of arranging the elements in a particular order, such as ascending or descending. This can be achieved using various algorithms like Bubble Sort, Selection Sort, or Insertion Sort. A menu-driven program allows users to select the desired sorting method dynamically.
7 min read