zsort

package module
v0.0.0-...-f62c9ca Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 28, 2023 License: MIT Imports: 1 Imported by: 0

README

Package zsort provides useful additions to the sort package

Super early stage, not for production use yet!

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Partial

func Partial[S ~[]E, E cmp.Ordered](x S, n int)

Partial sorts the first n elements of x, such that they are the smallest n elements in ascending order, using the type's natural ordering. The remaining elements in the slice are not sorted but are guaranteed to be greater than or equal to the elements in the first n positions.

x is sorted in-place. The sort is not guaranteed to be stable: equal elements may be reversed from their original order

Example
package main

import (
	"fmt"

	"github.com/arl/zsort"
)

func main() {
	s := []int{5, 2, 6, 3, 1, 4, 0, 9, 8, 7}

	zsort.Partial(s, 3)

	fmt.Println(s[:3])
}
Output:

[0 1 2]

func PartialFunc

func PartialFunc[S ~[]E, E any](x S, n int, less func(E, E) bool)

PartialFunc sorts the first n elements of x, such that they are the smallest n elements, given the provided less function. The remaining elements in the slice are not sorted but are guaranteed to be greater than or equal to the elements in the first n positions.

x is sorted in-place. The sort is not guaranteed to be stable: equal elements may be reversed from their original order

Example
package main

import (
	"fmt"

	"github.com/arl/zsort"
)

func main() {
	type person struct {
		name string
		age  int
	}

	persons := []person{
		{"Alice", 19},
		{"Bob", 17},
		{"Jane", 36},
		{"Henri", 24},
		{"Sandra", 22},
	}

	zsort.PartialFunc(persons, 3, func(p1, p2 person) bool { return p1.age > p2.age })

	fmt.Println(persons[:3])
}
Output:

[{Jane 36} {Henri 24} {Sandra 22}]

func Partition

func Partition[S ~[]E, E any](x S, pred func(int) bool) int

Partition rearranges the elements of x so that all elements for which pred returns true are placed before all elements for which pred returns false. There is no guarantee about the order of the elements within each partition. Partition returns the index of the first element in the second partition.

Note that the predicate receives the index of the element in the slice, not the element itself.

Example
package main

import (
	"fmt"

	"github.com/arl/zsort"
)

func main() {
	s := []int{7, 1, 1, 7, 1, 1, 7}

	split := zsort.Partition(s, func(i int) bool { return s[i] >= 3 })

	fmt.Println("split =", split)
	fmt.Println(s)

}
Output:

split = 3
[7 7 7 1 1 1 1]

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL