From 62254180744e2423419518fa7f8a0529d1bd994a Mon Sep 17 00:00:00 2001 From: duckjiangwei <365039476@qq.com> Date: Thu, 21 Dec 2023 10:02:23 +0800 Subject: [PATCH] improvement:optimize bubble sort (#152) --- algorithm/sort.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/algorithm/sort.go b/algorithm/sort.go index aaf2f459..23d295fe 100644 --- a/algorithm/sort.go +++ b/algorithm/sort.go @@ -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 + } } }