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

Published on 12 May 2024 09:40 PM

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

Source code in the echolisp programming language

(define (median L) ;; O(n log(n))
	(set! L (vector-sort! < (list->vector L)))
	(define dim (// (vector-length L) 2))
	(if (integer? dim)
		(// (+ [L dim] [L (1- dim)]) 2)
		[L (floor dim)]))

(median '( 3 4 5))
   → 4
(median '(6 5 4 3))
   → 4.5
(median (iota 10000))
   → 4999.5
(median (iota 10001))
   → 5000


  

You may also check:How to resolve the algorithm Vampire number step by step in the Python programming language
You may also check:How to resolve the algorithm Generate lower case ASCII alphabet step by step in the Maxima programming language
You may also check:How to resolve the algorithm Reflection/List methods step by step in the Wren programming language
You may also check:How to resolve the algorithm Increment a numerical string step by step in the Io programming language
You may also check:How to resolve the algorithm Anti-primes step by step in the Scala programming language