Click here to Skip to main content
15,896,557 members
Articles / Programming Languages / C#

Back to Basics - Generic Data Structures and Algorithms In .NET 2.0

Rate me:
Please Sign up or sign in to vote.
4.96/5 (93 votes)
23 Apr 2007Ms-PL15 min read 279.6K   2.6K   300  
Implementations of generic data structures and algorithms in .NET 2.0.
using System;
using System.Collections.Generic;
using System.Text;

namespace DataStructuresDotNet.Sorting
{
	public sealed class InsertionSorter<T> : Sorter<T>
	{
		#region Construction

		/// <summary>
		/// Initializes a new instance of the <see cref="InsertionSorter&lt;T&gt;"/> class.
		/// </summary>
		public InsertionSorter() { }

		#endregion

		#region Private Members

		private void Insert(IList<T> list, int sortedSequenceLength, T val, IComparer<T> comparer) {
			int i = sortedSequenceLength - 1;

			while ((i >= 0) && (comparer.Compare(list[i], val) > 0))
			{
				list[i + 1] = list[i];
				i--;
			}

			list[i + 1] = val;
		}

		#endregion

		#region Sorter<T> Members

		public override void Sort(IList<T> list, IComparer<T> comparer)
		{
			if (list == null)
			{
				throw new ArgumentNullException("list");
			}

			if (comparer == null)
			{
				throw new ArgumentNullException("comparer");
			}

			Sort(list, comparer, 0, list.Count - 1);
		}

		public void Sort(IList<T> list, IComparer<T> comparer, int start, int end)
		{
			if (end - start + 1 <= 1)
			{
				return;
			}

			int counter = start;

			while (counter < end + 1)
			{
				Insert(list, counter, list[counter], comparer);
				counter++;
			}
		}

		#endregion
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Microsoft Public License (Ms-PL)


Written By
Web Developer
South Africa South Africa
The author is a software consultant in South Africa, specializing in bespoke software solutions.

Comments and Discussions