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

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Averages/Median step by step in the Elena 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 Elena programming language

Source code in the elena programming language

import system'routines;
import system'math;
import extensions;
 
extension op 
{
    get Median()
    {
        var sorted := self.ascendant();

        var len := sorted.Length;
        if (len == 0)
        { 
            ^ nil 
        }
        else
        {
            var middleIndex := len / 2;
            if (len.mod:2 == 0)
            { 
                ^ (sorted[middleIndex - 1] + sorted[middleIndex]) / 2 
            }
            else
            { 
                ^ sorted[middleIndex] 
            }
        }
    }
}    

public program()
{
    var a1 := new real[]{4.1r, 5.6r, 7.2r, 1.7r, 9.3r, 4.4r, 3.2r};
    var a2 := new real[]{4.1r, 7.2r, 1.7r, 9.3r, 4.4r, 3.2r};
    
    console.printLine("median of (",a1.asEnumerable(),") is ",a1.Median);
    console.printLine("median of (",a2.asEnumerable(),") is ",a2.Median);
    
    console.readChar()
}

  

You may also check:How to resolve the algorithm Flatten a list step by step in the Crystal programming language
You may also check:How to resolve the algorithm Gauss-Jordan matrix inversion step by step in the Lambdatalk programming language
You may also check:How to resolve the algorithm Cartesian product of two or more lists step by step in the Phix programming language
You may also check:How to resolve the algorithm Inheritance/Multiple step by step in the PureBasic programming language
You may also check:How to resolve the algorithm Remove duplicate elements step by step in the Visual FoxPro programming language