Sunday, December 5, 2010

Selection Sort


The algorithm works as follows:
  • Find the minimum value in the list
  • Swap it with the value in the first position
  • Repeat the steps above for the remainder of the list (starting at the second position and advancing each time)
Effectively, the list is divided into two parts: the sublist of items already sorted, which is built up from left to right and is found at the beginning, and the sublist of items remaining to be sorted, occupying the remainder of the array.

public IList SelectionSort(IList arrayToSort)
{
    int min;
    for (int i = 0; i < arrayToSort.Count; i++)
    {

        min = i;
        for (int j = i + 1; j < arrayToSort.Count; j++)
        {
            if (((IComparable)arrayToSort[j]).CompareTo(arrayToSort[min]) < 0)
            {
                min = j;
            }
        }
        object temp = arrayToSort[i];
        arrayToSort[i] = arrayToSort[min];
        arrayToSort[min] = temp;

        RedrawItem(i);
        RedrawItem(min);
        pnlSamples.Refresh();
        if (chkCreateAnimation.Checked)
            SavePicture();    
    }

    return arrayToSort;
}

No comments:

Post a Comment