Averages/Median: Difference between revisions

→‎{{header|Go}}: add partial sort, quickselect examples
No edit summary
(→‎{{header|Go}}: add partial sort, quickselect examples)
Line 1,369:
# 85/2</lang>
=={{header|Go}}==
===Sort===
Go built-in sort. O(n log n).
<lang go>package main
 
Line 1,389 ⟶ 1,391:
}
return m
}</lang>
===Partial selection sort===
 
The task description references the WP entry for "selection algorithm" which (as of this writing) gives just one pseudocode example, which is implemented here. As the WP article notes, it is O(kn).
Unfortunately in the case of median, k is n/2 so the algorithm is O(n^2). Still, it gives the idea of median by selection. Note that the partial selection sort does leave the k smallest values sorted, so in the case of an even number of elements, the two elements to average are available after a single call to sel().
 
<lang go>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]
}</lang>
===Quickselect===
It doesn't take too much more code to implement a quickselect with random pivoting, which should run in expected time O(n). The qsel function here permutes elements of its parameter "a" in place. It leaves the slice somewhat more ordered, but unlike the sort and partial sort examples above, does not guarantee that element k-1 is in place. For the case of an even number of elements then, median must make two separate qsel() calls.
<lang go>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]
}</lang>
 
1,707

edits