Tuesday, July 22, 2008

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.

publicinterfaceISortStrategywhere T : IComparable

{

List Sort(IEnumerable input);

}

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

Thursday, July 17, 2008

After implementation of the Insertion and Shell Sort, this article explains the implementation of the other three famous sorting algorithms (Merge sort, Heap sort and Quick sort).

Merge Sort

Merge sort works by comparing every two elements and swapping them if the first should come after the second. It then merges each of the resulting lists of two into lists of four, then merges those lists of four, and so on; until at last two lists are merged into the final sorted list. Merge sort uses recursion for sorting the list.

The implementation of MergeSorter class

publicclassMergeSorterwhere T : IComparable

{

List tempList;

publicList Sort(IEnumerable input)

{

List inputItems = newList(input);

tempList = newList(inputItems.Count);

for (int i = 0; i <>

tempList.Add(default(T));

MergeSort(ref inputItems, 0, inputItems.Count - 1);

return inputItems;

}

privatevoid Merge(refList inputList, int left, int middle, int right)

{

int i;

int j;

for (i = middle + 1; i > left; i--)

{

tempList[i - 1] = inputList[i - 1];

}

for (j = middle; j <>

{

tempList[right + middle - j] = inputList[j + 1];

}

for (int k = left; k <= right; k++)

{

// Less Than

if (tempList[j].CompareTo(tempList[i]) == -1)

{

inputList[k] = tempList[j--];

}

else

{

inputList[k] = tempList[i++];

}

}

}

privatevoid MergeSort(refList a, int left, int right)

{

if (right <= left) return;

int middle = (right + left) / 2;

//recursive sorting

MergeSort(ref a, left, middle);

MergeSort(ref a, middle + 1, right);

Merge(ref a, left, middle, right);

}

}

Heap Sort

The heap sort works by determining the largest (or smallest) element of the list, placing that at the end (or beginning) of the list, then continuing with the rest of the list, but accomplishes this task efficiently by using a data structure called a binary tree (heap). Once the data list has been made into a heap, the root node is guaranteed to be the largest element. When it is removed and placed at the end of the list, the heap is rearranged so the largest element remaining moves to the root.

Quick sort uses the algorithm that partitions an array to choose an element, called a pivot, move all smaller elements before the pivot, and move all greater elements after it. It then uses recursion to follow the same algorithm to finally create a sorted list of elements.

The implementation of QuickSorter class

publicclassQuickSorterwhere T : IComparable

{

publicList Sort(IEnumerable input)

{

List sorteditems = newList(input);

QuickSort(ref sorteditems, 0, sorteditems.Count - 1);

return sorteditems;

}

privatevoid QuickSort(refList sortedItems, int left, int right)

{

if (right <= left) return;

int i = Partition(ref sortedItems, left, right);

QuickSort(ref sortedItems, left, i - 1);

QuickSort(ref sortedItems, i + 1, right);

}

privateint Partition(refList a, int l, int r)

{

T tmp;

int i = l - 1;

int j = r;

T v = a[r];for (; ; )

{

while (a[++i].CompareTo(v) == -1)

{

}

while (v.CompareTo(a[--j]) == -1)

{

if (j == l) break;

}

if (i >= j) break;

tmp = a[i];

a[i] = a[j];

a[j] = tmp;

}

a[r] = a[i];

a[i] = v;

return i;

}

}

In the next series of this article, i will show how to use strategy pattern to select the sorting algorithms we have implemented.

Wednesday, July 16, 2008

Model view controller is a classic pattern that is used in applications that need ability to maintain multiple views with same data. It can be used as an architectural pattern as well as a design pattern. MVC helps us to decouple the presentation layer and business layer (domain logic layer). The presentation layer is further divided into the View and Controller.

The MVC abstraction can be graphically explained as given below:

The main participants are

Model:The business entity/ domain data on which the application operates.Many applications use a persistent storage mechanism (such as a database) to store data. MVC does not specifically mention the data access layer because it is understood to be underneath or encapsulated by the Model.

View:The user interface that renders the model into a form of interaction.

Controller:Handles a request from a view and updates the model resulting a change in Model’s state.

To implement MVC in .NET we need mainly three classes (View, Controller and the Model). This example is implemented using interfaces that will allow me to make my application loosely coupled.

I have the interfaces (IView, IModel, IController) implemented as

publicinterfaceIView

{

//Method to change the state of view according to the model changes

void UpdateView(IModel model);

//These methods are used by the controller to change the state of view

void SalaryIncreased(Boolean increased);

void CompanyChanged(Boolean changed);

void DesignationChanged(Boolean changed);

}

publicinterfaceIModel

{

String UserName { get; set; }

String Company { get; set; }

String Designation { get; set; }

Int32 Salary { get; set; }

//Implementing the observer pattern. The model uses an observer

//pattern implementation to notify the views about the changes in the

//model

void AddObserver(IView view);

void RemoveObserver(IView view);

void Notify();

//Observer pattern implementation methods. End

}

publicinterfaceIController

{

//The methods to change the state of Model

void ChangeSalary(Int32 salary);

void ChangeCompany(String company);

void ChagneDesignation(String designation);

//Storing the Model and View instances in the controller

IModel Model { get; set; }

IView View { get; set; }

}

In my sample application I have a User class (Model) and a Form that helps users to change the User properties (View). I also have a UserController class that acts as a controller for the View.

The model

publicclassUser:IModel

{

privateString userName;

privateString company;

privateString designation;

privateInt32 salary;

//List of observers. You can add the views that should be notified the change on Model in this