mirror of
https://github.com/duke-git/lancet.git
synced 2026-03-01 00:35:28 +08:00
improvement:optimize bubble sort (#152)
This commit is contained in:
@@ -9,12 +9,17 @@ import "github.com/duke-git/lancet/v2/lancetconstraints"
|
|||||||
// Play: https://go.dev/play/p/GNdv7Jg2Taj
|
// Play: https://go.dev/play/p/GNdv7Jg2Taj
|
||||||
func BubbleSort[T any](slice []T, comparator lancetconstraints.Comparator) {
|
func BubbleSort[T any](slice []T, comparator lancetconstraints.Comparator) {
|
||||||
for i := 0; i < len(slice); i++ {
|
for i := 0; i < len(slice); i++ {
|
||||||
|
breakTag := false
|
||||||
for j := 0; j < len(slice)-1-i; j++ {
|
for j := 0; j < len(slice)-1-i; j++ {
|
||||||
isCurrGreatThanNext := comparator.Compare(slice[j], slice[j+1]) == 1
|
isCurrGreatThanNext := comparator.Compare(slice[j], slice[j+1]) == 1
|
||||||
if isCurrGreatThanNext {
|
if isCurrGreatThanNext {
|
||||||
swap(slice, j, j+1)
|
swap(slice, j, j+1)
|
||||||
|
breakTag = true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if !breakTag {
|
||||||
|
break
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user