1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-09 15:12:26 +08:00

feat: add Sort function for slice

This commit is contained in:
dudaodong
2022-12-01 22:46:56 +08:00
parent d66f92cd68
commit ec27ad4c40
4 changed files with 77 additions and 1 deletions

View File

@@ -3,6 +3,8 @@ package slice
import (
"fmt"
"reflect"
"github.com/duke-git/lancet/v2/lancetconstraints"
)
// sliceValue return the reflect value of a slice
@@ -24,3 +26,40 @@ func sliceElemType(reflectType reflect.Type) reflect.Type {
reflectType = reflectType.Elem()
}
}
func quickSort[T lancetconstraints.Ordered](slice []T, lowIndex, highIndex int, order string) {
if lowIndex < highIndex {
p := partition(slice, lowIndex, highIndex, order)
quickSort(slice, lowIndex, p-1, order)
quickSort(slice, p+1, highIndex, order)
}
}
// partition split slice into two parts for quick sort
func partition[T lancetconstraints.Ordered](slice []T, lowIndex, highIndex int, order string) int {
p := slice[highIndex]
i := lowIndex
for j := lowIndex; j < highIndex; j++ {
if order == "desc" {
if slice[j] > p {
swap(slice, i, j)
i++
}
} else {
if slice[j] < p {
swap(slice, i, j)
i++
}
}
}
swap(slice, i, highIndex)
return i
}
// swap two slice value at index i and j
func swap[T any](slice []T, i, j int) {
slice[i], slice[j] = slice[j], slice[i]
}