Skip to content

Commit

Permalink
增加sort排序,可以排序所有数字数组
Browse files Browse the repository at this point in the history
  • Loading branch information
name committed Oct 24, 2022
1 parent 4991341 commit fd509a9
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
18 changes: 18 additions & 0 deletions sort/sort.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package sort

import "sort"

// IntSlice attaches the methods of Interface to []T byte | int | int8 | int16 | int32 | int64 | uint | uintptr | uint16 | uint32 | uint64 | float32 | float64
// , sorting in increasing order.
type NumberSlice[T byte | int | int8 | int16 | int32 | int64 | uint | uintptr | uint16 | uint32 | uint64 | float32 | float64] []T

func (x NumberSlice[T]) Len() int { return len(x) }
func (x NumberSlice[T]) Less(i, j int) bool { return x[i] < x[j] }
func (x NumberSlice[T]) Swap(i, j int) { x[i], x[j] = x[j], x[i] }

// Sort is a convenience method: x.Sort() calls Sort(x).
func (x NumberSlice[T]) Sort() { Sort(x) }

func Sort[T byte | int | int8 | int16 | int32 | int64 | uint | uintptr | uint16 | uint32 | uint64 | float32 | float64](arr []T) {
sort.Sort(NumberSlice[T](arr))
}
20 changes: 20 additions & 0 deletions sort/sort_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package sort

import (
"log"
"testing"
)

func TestSort(t *testing.T) {
ints := []int{0, 1, 23, 4, 5, 6, 3}
Sort[int](ints)
log.Println(ints)

uints := []uint{0, 1, 23, 4, 5, 6, 3}
Sort[uint](uints)
log.Println(uints)

uint64s := []uint64{0, 1, 23, 4, 5, 6, 3}
Sort[uint64](uint64s)
log.Println(uint64s)
}

0 comments on commit fd509a9

Please sign in to comment.