lördag 28 juni 2014

Selection sort in C#

Selection sort - overview

Selection sort is an in-place comparison sort and it is quite simple and intuitive. It is inefficient for large lists and should thus only be used for arrays with a small numbers of items.

Description of the selection sort algorithm

Selection sort views the input array as two separate sublists. The list to the left contains the values that are already sorted. The values are sorted from left to right.

The list to the right contains the values remaining to be sorted.

Initially the array to the left is empty and the rest of the list constitutes the full input array.

Next, the algorithm will loop through all positions in the array from left to right and for each value it tries to find the smallest value in the right sublist and change places with the value at the current position.

Computational complexity

It is easy to show that selection sort has has a complexity of  O(n2) for all cases.

Example of an implementation of selection sort in C#


    private void SortArrayWithSelectionSort()
    {
        int[] array = { 7, 5, 23, 2, 0 };
        SelectionSort(array);

        // PrintResult(array);
    }

    private void SelectionSort(int[] a)
    {
        int minPos;
        int minVal;

        for (int i = 0; i < a.Length - 1; i++)
        {
            minPos = i;
            minVal = a[i];

            for (int j = i + 1; j < a.Length; j++)
            {
                if (a[j] < a[i] && a[j] < minVal)
                {
                    minPos = j;
                    minVal = a[j];
                }
            }

            SwapValues(a, i, minPos);
        }
    }

    private void SwapValues(int[] a, int i, int j)
    {
        int temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }




Inga kommentarer:

Skicka en kommentar