How to resolve the algorithm Averages/Median step by step in the E programming language

Published on 12 May 2024 09:40 PM
#E

How to resolve the algorithm Averages/Median step by step in the E programming language

Table of Contents

Problem Statement

Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle values. There are several approaches to this.   One is to sort the elements, and then pick the element(s) in the middle. Sorting would take at least   O(n logn).   Another approach would be to build a priority queue from the elements, and then extract half of the elements to get to the middle element(s).   This would also take   O(n logn).   The best solution is to use the   selection algorithm   to find the median in   O(n)   time. Quickselect_algorithm

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Averages/Median step by step in the E programming language

Source code in the e programming language

def median(list) {
    def sorted := list.sort()
    def count := sorted.size()
    def mid1 := count // 2
    def mid2 := (count - 1) // 2
    if (mid1 == mid2) {          # avoid inexact division
        return sorted[mid1]
    } else {
        return (sorted[mid1] + sorted[mid2]) / 2
    }
}

? median([1,9,2])
# value: 2

? median([1,9,2,4])
# value: 3.0

  

You may also check:How to resolve the algorithm Binary search step by step in the E programming language
You may also check:How to resolve the algorithm File size step by step in the E programming language
You may also check:How to resolve the algorithm List comprehensions step by step in the E programming language
You may also check:How to resolve the algorithm Active object step by step in the E programming language
You may also check:How to resolve the algorithm Test a function step by step in the E programming language