Tuesday 12 August 2014

Selection sort in C#

Selection Sort:
It is essentially an in-place comparison sort. It has O(n2) complexity, making it inefficient on large lists, and generally performs worse than the similar Insertion Sort. Selection sort is noted for its simplicity, and also has performance advantages over more complicated algorithms in certain situations. It performs better than Bubble Sort in almost all cases.

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace DataStructureAlgoriths
{
    class Sort
    {
public void SelectionSort()
        {
            long[] inputArray = new long[] { 4, 9, 8, 6, 3, 2, 1 };
            long index_of_min = 0;
            for (int iterator = 0; iterator < inputArray.Length - 1; iterator++)
            {
                index_of_min = iterator;
                for (int index = iterator + 1; index < inputArray.Length; index++)
                {
                    if (inputArray[index] < inputArray[index_of_min])
                    {
                        index_of_min = index;
                    }
                }
                Swap(ref inputArray[iterator], ref inputArray[index_of_min]);
            }
            foreach (var item in inputArray)
            {
                Console.WriteLine(item);
            }
        }
public void Swap(ref long valOne, ref long valTwo)
        {
            valOne = valOne + valTwo;
            valTwo = valOne - valTwo;
            valOne = valOne - valTwo;
        }
}
}

using System;
using System.Collections.Generic;
using System.Text;

namespace DataStructureAlgoriths
{
    class Program
    {
        static void Main(string[] args)
        {
            Sort s = new Sort();
            s.SelectionSort();
            Console.ReadLine();
        }
    }

}

No comments:

Post a Comment