Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Median of an array? Best solution to keep track of median

Numbers are randomly generated and stored into an expanding array. How do you keep track of the median?

Ideas:
Array
Binary Tree
Heap

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

There’s a wide variety of options for programming in general, but since we’re working with JS the straightforward way is to simply keep an array and insert elements in sorted order, something like:

class Median {
  arr = []
  insert(i) {
    let l = 0,
      r = this.arr.length
    while (l < r) {
      const m = (l + r) >>> 1
      if (this.arr[m] < i) l = m + 1
      else r = m
    }
    this.arr.splice(l, 0, i)
  }
  get median() {
    const mid = (this.arr.length / 2) | 0
    return this.arr.length ?
      this.arr[mid] : (this.arr[mid - 1] + this.arr[mid]) / 2
  }
}

const m = new Median;
[2, 8, 8, -2, 19].forEach(m.insert.bind(m))
console.log(m.median)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading