Tuesday, July 22, 2008

Generic implementation of sorting algorithms and using Strategy pattern - End

This is the last part of the Sorting algorithm implementation series. In this post i will show the implementation of Strategy pattern and how to use the pattern for accessing the sorting implementations we had created.


Strategy pattern defines a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it. The Strategy pattern enables a client to choose which algorithm to use from a family of algorithms and gives it a simple way to access it.

To implement a Strategy I will create an Interface ISortStrategy that exposes a Sort method for any collection that implements IComparable.

public interface ISortStrategy where T : IComparable

{

List Sort(IEnumerable input);

}

And each of the classes that have different sorting algorithm implementations will be implemented from this interface

Eg:

public class BubbleSorter : ISortStrategy where T : IComparable

{

#region ISortStrategy Members

public List Sort(IEnumerable input)

{

List sortItems = new List(input);

Int32 right = sortItems.Count - 1;

do

{

Int32 lastSwap = 0;

for (Int32 i = 0; i <>

{

if (sortItems[i].CompareTo(sortItems[i + 1]) > 0)

{

T temp = sortItems[i];

sortItems[i] = sortItems[i + 1];

sortItems[i + 1] = temp;

lastSwap = i;

}

}

right = lastSwap;

}

while (right > 0);

return sortItems;

}

#endregion

}

In the client code I can access a strategy like

ISortStrategy<Employee> sortStrategy = default(ISortStrategy<Employee>);

String category = "Heap";

switch (category)

{

case "Bubble":

sortStrategy = new BubbleSorter<Employee>();

break;

case "Merge":

sortStrategy = new MergeSorter<Employee>();

break;

case "Heap":

sortStrategy = new HeapSorter<Employee>();

break;

case "Quick":

sortStrategy = new QuickSorter<Employee>();

break;

case "Selection":

sortStrategy = new SelectionSorter<Employee>();

break;

}

List<Employee> sortedList = sortStrategy.Sort(emps);

No comments: