Skip to content

Commit

Permalink
improvement:optimize bubble sort
Browse files Browse the repository at this point in the history
  • Loading branch information
duckjiangwei committed Dec 20, 2023
1 parent 0b976e9 commit a72ee4b
Showing 1 changed file with 5 additions and 0 deletions.
5 changes: 5 additions & 0 deletions algorithm/sort.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}
}

Expand Down

0 comments on commit a72ee4b

Please sign in to comment.