| | 1 | | namespace MoreStructures.Lists.Sorting; |
| | 2 | |
|
| | 3 | | /// <summary> |
| | 4 | | /// Extensions methods for <see cref="IList{T}"/>, in the context of list sorting. |
| | 5 | | /// </summary> |
| | 6 | | public static class Extensions |
| | 7 | | { |
| | 8 | | /// <summary> |
| | 9 | | /// Verifies that the provided <paramref name="list"/> is sorted. |
| | 10 | | /// </summary> |
| | 11 | | /// <typeparam name="T">The type of items of <paramref name="list"/>.</typeparam> |
| | 12 | | /// <param name="list">The <see cref="IList{T}"/> to check.</param> |
| | 13 | | /// <returns> |
| | 14 | | /// <see langword="true"/> if <paramref name="list"/> is sorted, <see langword="false"/> otherwise. |
| | 15 | | /// </returns> |
| | 16 | | /// <remarks> |
| | 17 | | /// Zips the list with itself, shifted one item forward. |
| | 18 | | /// <br/> |
| | 19 | | /// Then checks whether each of the couples of the zip has a <see cref="ValueTuple{T, U}.Item1"/> non-bigger than |
| | 20 | | /// <see cref="ValueTuple{T, U}.Item2"/>. |
| | 21 | | /// <br/> |
| | 22 | | /// Stops at the first encountered. |
| | 23 | | /// <br/> |
| | 24 | | /// Time Complexity is O(n), when fully enumerated and in the worst case. Space Complexity is O(1). |
| | 25 | | /// </remarks> |
| | 26 | | public static bool IsSorted<T>(this IList<T> list) |
| | 27 | | where T : IComparable<T> => |
| 1766 | 28 | | list.Zip(list.Skip(1)).All(c => c.First.CompareTo(c.Second) <= 0); |
| | 29 | |
|
| | 30 | | /// <inheritdoc cref="IsSorted{T}(IList{T})" path="//*[not(self::summary or self::remarks)]"/> |
| | 31 | | /// <summary> |
| | 32 | | /// Verifies that the provided <paramref name="list"/> is sorted, using the provided <paramref name="comparer"/>. |
| | 33 | | /// </summary> |
| | 34 | | /// <param name="list">The <see cref="IList{T}"/> to check.</param> |
| | 35 | | /// <param name="comparer"> |
| | 36 | | /// The <see cref="IComparer{T}"/> to be used to comparer <typeparamref name="T"/> instances. |
| | 37 | | /// </param> |
| | 38 | | /// <remarks> |
| | 39 | | /// <inheritdoc cref="IsSorted{T}(IList{T})"/> |
| | 40 | | /// </remarks> |
| | 41 | | public static bool IsSorted<T>(this IList<T> list, IComparer<T> comparer) => |
| 1209 | 42 | | list.Zip(list.Skip(1)).All(c => comparer.Compare(c.First, c.Second) <= 0); |
| | 43 | | } |