ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

bool IsSorted (Comparison<T> comparison)

returns true if a sequence is sorted

Source

public static bool IsSorted<T> (this IEnumerable<T> @this, Comparison<T> comparison = null)
{
	if (comparison == null)
		comparison = Comparer<T>.Default.Compare;

	using (IEnumerator<T> e = @this.GetEnumerator ())
	{
		if (!e.MoveNext ())
			return true;

		T prev = e.Current;
		while (e.MoveNext ())
		{
			T current = e.Current;
			if (comparison (prev, current) > 0)
				return false;

			prev = current;
		}
	}
	return true;
}

Example

Console.WriteLine (Enumerable.Range (0, 10000).IsSorted ());

Author: Piers Haken

Submitted on: 30 okt. 2010

Language: C#

Type: System.Collections.Generic.IEnumerable<T>

Views: 5048