How to resolve the algorithm Averages/Median step by step in the ReScript programming language
How to resolve the algorithm Averages/Median step by step in the ReScript 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 ReScript programming language
Source code in the rescript programming language
let median = (arr) =>
{
let float_compare = (a, b) => {
let diff = a -. b
if diff == 0.0 { 0 } else
if diff > 0.0 { 1 } else { -1 }
}
let _ = Js.Array2.sortInPlaceWith(arr, float_compare)
let count = Js.Array.length(arr)
// find the middle value, or the lowest middle value
let middleval = ((count - 1) / 2)
let median =
if (mod(count, 2) != 0) { // odd number, middle is the median
arr[middleval]
} else { // even number, calculate avg of 2 medians
let low = arr[middleval]
let high = arr[middleval+1]
((low +. high) /. 2.0)
}
median
}
Js.log(median([4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2]))
Js.log(median([4.1, 7.2, 1.7, 9.3, 4.4, 3.2]))
You may also check:How to resolve the algorithm Perfect totient numbers step by step in the Racket programming language
You may also check:How to resolve the algorithm Order two numerical lists step by step in the Standard ML programming language
You may also check:How to resolve the algorithm Palindrome dates step by step in the Julia programming language
You may also check:How to resolve the algorithm Vector products step by step in the RPL programming language
You may also check:How to resolve the algorithm Sorting algorithms/Bogosort step by step in the Ursala programming language