Open In App

JavaScript Program to Find Median in a Stream of Integers (running integers) using Array

Last Updated : 12 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads