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

Published on 12 May 2024 09:40 PM

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

Source code in the objeck programming language

use Structure;

bundle Default {
  class Median {
    function : Main(args : String[]) ~ Nil {
      numbers := FloatVector->New([4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2]);
      DoMedian(numbers)->PrintLine();

      numbers := FloatVector->New([4.1, 7.2, 1.7, 9.3, 4.4, 3.2]);
      DoMedian(numbers)->PrintLine();
    }

    function : native : DoMedian(numbers : FloatVector) ~ Float {
      if(numbers->Size() = 0) {
        return 0.0;
      }
      else if(numbers->Size() = 1) {
        return numbers->Get(0);
      };
      
      numbers->Sort();

      i := numbers->Size() / 2;
      if(numbers->Size() % 2 = 0) {
        return (numbers->Get(i - 1) + numbers->Get(i)) / 2.0;              
      };
      
      return numbers->Get(i);
    }
  }
}

  

You may also check:How to resolve the algorithm Digital root step by step in the UNIX Shell programming language
You may also check:How to resolve the algorithm Sum and product of an array step by step in the ACL2 programming language
You may also check:How to resolve the algorithm Sequence of non-squares step by step in the Ursala programming language
You may also check:How to resolve the algorithm Palindrome dates step by step in the Lua programming language
You may also check:How to resolve the algorithm Read a specific line from a file step by step in the C++ programming language