sortx

package module
v1.0.11 Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2025 License: MIT Imports: 2 Imported by: 5

README

GitHub Workflow Status (branch) GoDoc Coverage Status Supported Go Versions GitHub Release Go Report Card

sortx

sortx is a Go package that provides a simple and flexible approach to sort slices using custom comparison functions. It leverages Go's generics and the sort.Interface to avoid repeating the implementation of sorting logic for different types.


CHINESE README

中文说明

Installation

To install the sortx package, you can use the following command:

go get github.com/yyle88/sortx

Usage

The package offers multiple functions for sorting slices with different comparison strategies. Below are the main functions available:

SortByIndex

Sorts the slice a using an index-based comparison function iLess.

sortx.SortByIndex(a []V, iLess func(i, j int) bool)
  • a: The slice to be sorted.
  • iLess: The function that compares the indices of two elements in the slice.
  • Sorts the slice in place using the provided index-based comparison function.
SortByValue

Sorts the slice a using a value-based comparison function vLess.

sortx.SortByValue(a []V, vLess func(a, b V) bool)
  • a: The slice to be sorted.
  • vLess: The function that compares the values of two elements in the slice.
  • Sorts the slice in place using the provided value-based comparison function.
SortIStable

Sorts the slice a using an index-based comparison function iLess and preserves the sequence of same elements (stable sort).

sortx.SortIStable(a []V, iLess func(i, j int) bool)
  • a: The slice to be sorted.
  • iLess: The function that compares the indices of two elements in the slice.
  • Sorts the slice in place while maintaining the input sequence of same elements (stable sort).
SortVStable

Sorts the slice a using a value-based comparison function vLess and preserves the sequence of same elements (stable sort).

sortx.SortVStable(a []V, vLess func(a, b V) bool)
  • a: The slice to be sorted.
  • vLess: The function that compares the values of two elements in the slice.
  • Sorts the slice in place while maintaining the input sequence of same elements (stable sort).

Example

Basic Sorting

Sort integers and strings using index-based and value-based comparison:

package main

import (
	"fmt"

	"github.com/yyle88/sortx"
)

func main() {
	// Sort integers using index comparison
	numbers := []int{5, 3, 8, 1, 4}
	sortx.SortByIndex(numbers, func(i, j int) bool {
		return numbers[i] < numbers[j]
	})
	fmt.Println("Sorted using index:", numbers) // Output: [1 3 4 5 8]

	// Sort strings using value comparison
	fruits := []string{"apple", "banana", "orange", "date"}
	sortx.SortByValue(fruits, func(a, b string) bool {
		return a < b
	})
	fmt.Println("Sorted using value:", fruits) // Output: [apple banana date orange]
}

⬆️ Source: Source

Stable Sorting

Stable sort preserves input sequence of same elements:

package main

import (
	"fmt"

	"github.com/yyle88/sortx"
)

type Task struct {
	Name string
	Rank int
}

func main() {
	// Stable sort preserves input sequence of same elements
	tasks := []Task{
		{"Task-A", 2},
		{"Task-B", 1},
		{"Task-C", 2},
		{"Task-D", 1},
	}

	// Sort using Rank, same Rank keeps input sequence
	sortx.SortVStable(tasks, func(a, b Task) bool {
		return a.Rank < b.Rank
	})

	fmt.Println("Stable sorted tasks:")
	for _, task := range tasks {
		fmt.Printf("  %s (Rank: %d)\n", task.Name, task.Rank)
	}
	// Output:
	//   Task-B (Rank: 1)
	//   Task-D (Rank: 1)
	//   Task-A (Rank: 2)
	//   Task-C (Rank: 2)
}

⬆️ Source: Source

Examples

Custom Struct Sorting

Sort using struct field:

type Person struct {
	Name string
	Age  int
}
people := []Person{{"Alice", 30}, {"Bob", 25}}
sortx.SortByValue(people, func(a, b Person) bool {
	return a.Age < b.Age
})

Sort with multiple conditions:

sortx.SortByValue(people, func(a, b Person) bool {
	if a.Age != b.Age {
		return a.Age < b.Age
	}
	return a.Name < b.Name
})
Descending Sort

Sort in descending sequence:

numbers := []int{1, 5, 3, 9, 2}
sortx.SortByValue(numbers, func(a, b int) bool {
	return a > b // Use > for descending
})
Using sort.Interface

Create sort.Interface for advanced usage:

data := []int{5, 2, 8, 1}
sortable := sortx.NewSortByValue(data, func(a, b int) bool {
	return a < b
})
sort.Sort(sortable) // Use standard sort package

📄 License

MIT License - see LICENSE.


💬 Contact & Feedback

Contributions are welcome! Report bugs, suggest features, and contribute code:

  • 🐛 Mistake reports? Open an issue on GitHub with reproduction steps
  • 💡 Fresh ideas? Create an issue to discuss
  • 📖 Documentation confusing? Report it so we can improve
  • 🚀 Need new features? Share the use cases to help us understand requirements
  • Performance issue? Help us optimize through reporting slow operations
  • 🔧 Configuration problem? Ask questions about complex setups
  • 📢 Follow project progress? Watch the repo to get new releases and features
  • 🌟 Success stories? Share how this package improved the workflow
  • 💬 Feedback? We welcome suggestions and comments

🔧 Development

New code contributions, follow this process:

  1. Fork: Fork the repo on GitHub (using the webpage UI).
  2. Clone: Clone the forked project (git clone https://github.com/yourname/repo-name.git).
  3. Navigate: Navigate to the cloned project (cd repo-name)
  4. Branch: Create a feature branch (git checkout -b feature/xxx).
  5. Code: Implement the changes with comprehensive tests
  6. Testing: (Golang project) Ensure tests pass (go test ./...) and follow Go code style conventions
  7. Documentation: Update documentation to support client-facing changes
  8. Stage: Stage changes (git add .)
  9. Commit: Commit changes (git commit -m "Add feature xxx") ensuring backward compatible code
  10. Push: Push to the branch (git push origin feature/xxx).
  11. PR: Open a merge request on GitHub (on the GitHub webpage) with detailed description.

Please ensure tests pass and include relevant documentation updates.


🌟 Support

Welcome to contribute to this project via submitting merge requests and reporting issues.

Project Support:

  • Give GitHub stars if this project helps you
  • 🤝 Share with teammates and (golang) programming friends
  • 📝 Write tech blogs about development tools and workflows - we provide content writing support
  • 🌟 Join the ecosystem - committed to supporting open source and the (golang) development scene

Have Fun Coding with this package! 🎉🎉🎉


GitHub Stars

Stargazers

Documentation

Overview

Package sortx: Flexible slice sorting with custom comparison functions Provides sort.Interface implementation supporting both index-based and value-based comparisons Enables type-safe generic sorting without repeating boilerplate code

sortx: 灵活的切片排序工具,支持自定义比较函数 提供 sort.Interface 实现,支持基于索引和基于值的比较 实现类型安全的泛型排序,避免重复样板代码

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewSortByIndex

func NewSortByIndex[V any](a []V, iLess func(i, j int) bool) sort.Interface

NewSortByIndex creates a sort.Interface using index-based comparison Panics when iLess is nil to detect invalid input at construction time

NewSortByIndex 使用索引比较函数创建 sort.Interface 当 iLess 为 nil 时触发 panic,在构造时检测无效输入

func NewSortByValue

func NewSortByValue[V any](a []V, vLess func(a, b V) bool) sort.Interface

NewSortByValue creates a sort.Interface using value-based comparison Panics when vLess is nil to detect invalid input at construction time

NewSortByValue 使用值比较函数创建 sort.Interface 当 vLess 为 nil 时触发 panic,在构造时检测无效输入

func SortByIndex

func SortByIndex[V any](a []V, iLess func(i, j int) bool)

SortByIndex sorts the slice using index-based comparison Compares elements at given indices

SortByIndex 使用索引比较对切片排序 通过给定索引比较元素

func SortByValue

func SortByValue[V any](a []V, vLess func(a, b V) bool)

SortByValue sorts the slice using value-based comparison Compares elements using values

SortByValue 使用值比较对切片排序 通过值比较元素

func SortIStable

func SortIStable[V any](a []V, iLess func(i, j int) bool)

SortIStable sorts the slice with stable mode using index-based comparison Same elements remain in input sequence

SortIStable 使用索引比较对切片进行稳定排序 相同元素保持输入时的顺序

func SortVStable

func SortVStable[V any](a []V, vLess func(a, b V) bool)

SortVStable sorts the slice with stable mode using value-based comparison Same elements remain in input sequence

SortVStable 使用值比较对切片进行稳定排序 相同元素保持输入时的顺序

Types

type Slice

type Slice[V any] struct {
	// contains filtered or unexported fields
}

Slice represents a sortable slice with custom comparison functions Supports both index-based and value-based comparison strategies

Slice 表示一个可排序的切片,支持自定义比较函数 支持基于索引和基于值的比较策略

func (*Slice[V]) Len

func (s *Slice[V]) Len() int

Len returns the slice length

Len 返回切片长度

func (*Slice[V]) Less

func (s *Slice[V]) Less(i, j int) bool

Less compares elements at indexes i and j Uses iLess when set, otherwise uses vLess

Less 比较索引 i 和 j 处的元素 优先使用 iLess,否则使用 vLess

func (*Slice[V]) Swap

func (s *Slice[V]) Swap(i, j int)

Swap exchanges elements at indexes i and j

Swap 交换索引 i 和 j 处的元素

Directories

Path Synopsis
internal
demos/demo1x command
demos/demo2x command

Jump to

Keyboard shortcuts

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