ideas | discover | explore

Thursday, June 28, 2012

C# 15 - Selection sort

Implementing a sort using selection sort algorithm.

1. Create a new console project.
2. Edit the Program.cs inside static void Main(string[] args) file as shown below.

static void Main(string[] args)
{
    int[] array = { 3, 2, 1, 4, 8 };
    Console.Write("Before sort: ");
    PrintArray(array);
    Console.WriteLine();
    SelectionSort(array);
    Console.Write("After sort : ");
    PrintArray(array);
    Console.WriteLine();

    Console.ReadLine();

}

private static void SelectionSort(int[] sortArray)
{
    int smallest = 0;
    int smallestIndex = 0;

     /* advance the position through the entire array */
     /*   (could do i < n-1 because single element is also min element) */
     for (int i = 0; i < sortArray.Length; i++)
     {
          smallest = sortArray[i];//the smallest value is at index 0
          smallestIndex = i;//store the index of the smallest value

           //find the index of the smallest value
                for (int x = i + 1; x < sortArray.Length; x++)
                {
                    if (sortArray[x] < sortArray[i])
                        smallestIndex = x;
                }

                //swap/exchange the smallest value found with last index
                sortArray[i] = sortArray[smallestIndex];
                sortArray[smallestIndex] = smallest;
            }
        }


private static void PrintArray(int[] array)
{
     for (int i = 0; i < array.Length; i++)
     {
          Console.Write(array[i] + " ");
     }
}


3. Press F5 to run and see the results.


4. Thank you.

Reference(s):
http://en.wikipedia.org/wiki/Selection_sort
http://www.sorting-algorithms.com/selection-sort

2 comments:

inf3qt0r said...

if (sortArray[x] < sortArray[i])
{
smallestIndex = x;
sortArray[i] = sortArray[smallestIndex];
}

Unknown said...

Nice one inf3qt0r!