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

Published on 12 May 2024 09:40 PM
#Go

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

1. Median Calculation (median function)

The median function in the first code snippet calculates the median of a slice of float64 values. It takes a slice of numbers as input and returns the median value. The median is defined as the middle value in a sorted list. If the list has an even number of elements, the median is the average of the two middle values.

2. Sorting and Calculation (median function)

In this approach, the numbers are first sorted in ascending order using the sort.Float64s function. Then, the median is calculated based on the index of the middle element in the sorted slice. If the length of the slice is odd, the median is simply the value at the middle index. If the length is even, the median is the average of the values at the two middle indices.

3. Selection Algorithm (sel function)

This implementation uses a selection algorithm to find the median. The sel function takes a slice of numbers and a target index (k) as input and returns the k-th smallest number in the slice. The algorithm iterates over the slice and keeps track of the minimum value and its index. It swaps the minimum value with the value at the current index and continues the iteration until the target index is reached. Finally, it returns the value at the target index.

4. Quick Select Algorithm (qsel function)

The qsel function uses the Quick Select algorithm to find the median. This algorithm randomly selects a pivot value and partitions the slice into two sub-slices: one containing numbers less than the pivot and the other containing numbers greater than or equal to the pivot. It then recursively applies the algorithm to the appropriate sub-slice to find the k-th smallest number.

5. Example Usage

The main function demonstrates the usage of the median function. It creates a slice of numbers and prints the calculated median value.

The median function is a common statistical function used to find the middle value in a dataset. It is used in various applications, such as data analysis, machine learning, and statistics.

Source code in the go programming language

package main

import (
    "fmt"
    "sort"
)

func main() {
    fmt.Println(median([]float64{3, 1, 4, 1}))    // prints 2
    fmt.Println(median([]float64{3, 1, 4, 1, 5})) // prints 3
}

func median(a []float64) float64 {
    sort.Float64s(a)
    half := len(a) / 2
    m := a[half]
    if len(a)%2 == 0 {
        m = (m + a[half-1]) / 2
    }
    return m
}


package main

import "fmt"

func main() {
    fmt.Println(median([]float64{3, 1, 4, 1}))    // prints 2
    fmt.Println(median([]float64{3, 1, 4, 1, 5})) // prints 3
}

func median(a []float64) float64 {
    half := len(a) / 2
    med := sel(a, half)
    if len(a)%2 == 0 {
        return (med + a[half-1]) / 2
    }
    return med
}

func sel(list []float64, k int) float64 {
    for i, minValue := range list[:k+1] {
        minIndex := i
        for j := i + 1; j < len(list); j++ {
            if list[j] < minValue {
                minIndex = j
                minValue = list[j]
                list[i], list[minIndex] = minValue, list[i]
            }
        }
    }
    return list[k]
}


package main

import (
    "fmt"
    "math/rand"
)

func main() {
    fmt.Println(median([]float64{3, 1, 4, 1}))    // prints 2
    fmt.Println(median([]float64{3, 1, 4, 1, 5})) // prints 3
}

func median(list []float64) float64 {
    half := len(list) / 2
    med := qsel(list, half)
    if len(list)%2 == 0 {
        return (med + qsel(list, half-1)) / 2
    }
    return med
}

func qsel(a []float64, k int) float64 {
    for len(a) > 1 {
        px := rand.Intn(len(a))
        pv := a[px]
        last := len(a) - 1
        a[px], a[last] = a[last], pv
        px = 0
        for i, v := range a[:last] {
            if v < pv {
                a[px], a[i] = v, a[px]
                px++
            }
        }
        if px == k {
            return pv
        }
        if k < px {
            a = a[:px]
        } else {
            // swap elements.  simply assigning a[last] would be enough to
            // allow qsel to return the correct result but it would leave slice
            // "a" unusable for subsequent use.  we want this full swap so that
            // we can make two successive qsel calls in the case of median
            // of an even number of elements.
            a[px], a[last] = pv, a[px]
            a = a[px+1:]
            k -= px + 1
        }
    }
    return a[0]
}


  

You may also check:How to resolve the algorithm Count occurrences of a substring step by step in the Nemerle programming language
You may also check:How to resolve the algorithm Rep-string step by step in the Tcl programming language
You may also check:How to resolve the algorithm Fractran step by step in the BQN programming language
You may also check:How to resolve the algorithm Numerical integration step by step in the BBC BASIC programming language
You may also check:How to resolve the algorithm Integer sequence step by step in the Fish programming language