feat: add Sort function for slice

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

No files matched your search

+39
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]
}