public static IEnumerable <TSource> HeapSort <TSource>(this IEnumerable <TSource> source, bool descending = false) { if (source == null) { throw new ArgumentNullException(nameof(source)); } var heap = Heap1.Create(source, descending); while (heap.Any) { yield return(heap.Pop()); } }
public void SortDescending() { var values = RandomHelper.CreateData(100000); var actual = TimeHelper.Measure(() => Heap1.Create(values, true)); var a = new int[values.Length]; TimeHelper.Measure(() => { for (var i = 0; i < a.Length; i++, actual.Pop()) { a[i] = actual.First; } }); var e = TimeHelper.Measure(() => values.OrderByDescending(x => x).ToArray()); CollectionAssert.AreEqual(e, a); }
public void SortDescending_String() { var values = RandomHelper.CreateData(100000); var actual = TimeHelper.Measure(() => Heap1.Create(x => x.ToString(), values, true)); var a = new List <int>(); TimeHelper.Measure(() => { while (actual.Any) { a.Add(actual.Pop()); } }); var e = TimeHelper.Measure(() => values.OrderByDescending(x => x.ToString()).ToArray()); CollectionAssert.AreEqual(e, a); }
public void Sort() { var values = RandomHelper.CreateData(100000); var actual = TimeHelper.Measure(() => Heap1.Create(values)); var a = new int[values.Length]; TimeHelper.Measure(() => { for (var i = 0; i < a.Length; i++) { a[i] = actual.Pop(); } }); var e = (int[])values.Clone(); TimeHelper.Measure(() => Array.Sort(e)); CollectionAssert.AreEqual(e, a); }
public static IEnumerable <TSource> HeapSort <TSource, TKey>(this IEnumerable <TSource> source, Func <TSource, TKey> keySelector, bool descending = false) { if (source == null) { throw new ArgumentNullException(nameof(source)); } if (keySelector == null) { throw new ArgumentNullException(nameof(keySelector)); } var heap = Heap1.Create(v => v.k, source.Select(o => (o: o, k: keySelector(o))), descending); while (heap.Any) { yield return(heap.Pop().o); } }