From 979d12b9364666b503e1349ae4cfcebe8bfaa4ba Mon Sep 17 00:00:00 2001 From: hoangtruong Date: Sun, 13 Feb 2022 15:37:02 +0700 Subject: [PATCH] Update BubbleSorter.cs Optimization BubbleSort. No swap break for --- Algorithms/Sorting/BubbleSorter.cs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/Algorithms/Sorting/BubbleSorter.cs b/Algorithms/Sorting/BubbleSorter.cs index 83981475..920223ba 100644 --- a/Algorithms/Sorting/BubbleSorter.cs +++ b/Algorithms/Sorting/BubbleSorter.cs @@ -44,5 +44,26 @@ public static void BubbleSortDescending(this IList collection, Comparer } } } + + /// + /// Public API: Optimization + /// + public static void OptimizationBubbleSortDescending(this List collection,Comparer comparer) + { + for (int i = 0; i < collection.Count -1; i++) + { + bool noSwap = true; + for (int index = 0; index < collection.Count - 1; index++) + { + if(comparer.Compare(collection[index],collection[index - 1]) > 0) + { + collection.Swap(index - 1, index); + noSwap = false; + } + } + if(noSwap) + break; + } + } } }