1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-04 12:52:28 +08:00

improvement:optimize bubble sort (#152)

This commit is contained in:
duckjiangwei
2023-12-21 10:02:23 +08:00
committed by GitHub
parent 0b976e9a4c
commit 6225418074

View File

@@ -9,12 +9,17 @@ import "github.com/duke-git/lancet/v2/lancetconstraints"
// Play: https://go.dev/play/p/GNdv7Jg2Taj
func BubbleSort[T any](slice []T, comparator lancetconstraints.Comparator) {
for i := 0; i < len(slice); i++ {
breakTag := false
for j := 0; j < len(slice)-1-i; j++ {
isCurrGreatThanNext := comparator.Compare(slice[j], slice[j+1]) == 1
if isCurrGreatThanNext {
swap(slice, j, j+1)
breakTag = true
}
}
if !breakTag {
break
}
}
}