public void MaxLimitHeap_Works_Correctly(int heapSize, int itemCount) { var items = new string[itemCount]; for (var i = 0; i < itemCount; i++) { items[i] = Guid.NewGuid().ToString("N"); } var heap = new MaxLimitHeap <string>(heapSize); Assert.AreEqual(heap.AddAll(items), itemCount); Array.Sort(items); Array.Reverse(items); var minItems = new HashSet <string>(); var itemCounter = 0; for (var i = 0; i < Math.Min(heapSize, itemCount); i++) { minItems.Add(items[itemCounter++]); } itemCounter = 0; foreach (var current in heap.PopAll()) { Assert.IsTrue(minItems.Contains(current)); itemCounter++; } Assert.AreEqual(itemCounter, Math.Min(heapSize, itemCount)); }
/// <summary> /// Enumerates over given <paramref name="itemCollection"/> and finds the /// maximums (up to <paramref name="totalMaximums"/>) items using <paramref name="comparer"/>. /// Returns another enumerable based of required <paramref name="sorting"/>. /// </summary> /// <typeparam name="T">Type of the items in the input collection</typeparam> /// <param name="itemCollection">Input collection</param> /// <param name="totalMaximums">Count of total number of maximum to find. /// Error is thrown if value is negative or zero (0).</param> /// <param name="comparer">Comparer instance. If not provided, then <seealso cref="Comparer{T}.Default"/> will be used.</param> /// <param name="sorting">Output sorting (it uses <paramref name="comparer"/>). As the interest is only to find all the required /// number of maximums. It is best to use <seealso cref="SortOrder.None"/> as sorting value /// otherwise, an additional latency might be observed.</param> public static IEnumerable <T> FindMaximums <T>(this IEnumerable <T> itemCollection, int totalMaximums, IComparer <T> comparer = null, SortOrder sorting = SortOrder.None) { var heap = new MaxLimitHeap <T>(totalMaximums, comparer); heap.AddAll(itemCollection); return(heap.GetSorted(comparer, sorting, true)); }