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

Published on 12 May 2024 09:40 PM

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

Source code in the easylang programming language

proc quickselect k . list[] res .
   # 
   subr partition
      mid = left
      for i = left + 1 to right
         if list[i] < list[left]
            mid += 1
            swap list[i] list[mid]
         .
      .
      swap list[left] list[mid]
   .
   left = 1
   right = len list[]
   while left < right
      partition
      if mid < k
         left = mid + 1
      elif mid > k
         right = mid - 1
      else
         left = right
      .
   .
   res = list[k]
.
proc median . list[] res .
   h = len list[] div 2 + 1
   quickselect h list[] res
   if len list[] mod 2 = 0
      quickselect h - 1 list[] h
      res = (res + h) / 2
   .
.
test[] = [ 4.1 5.6 7.2 1.7 9.3 4.4 3.2 ]
median test[] med
print med
test[] = [ 4.1 7.2 1.7 9.3 4.4 3.2 ]
median test[] med
print med


  

You may also check:How to resolve the algorithm Catalan numbers/Pascal's triangle step by step in the Perl programming language
You may also check:How to resolve the algorithm Number reversal game step by step in the Rust programming language
You may also check:How to resolve the algorithm Sort using a custom comparator step by step in the Zig programming language
You may also check:How to resolve the algorithm First-class functions/Use numbers analogously step by step in the F# programming language
You may also check:How to resolve the algorithm Sorting algorithms/Heapsort step by step in the FreeBASIC programming language