Distribution Sort - CSharp Data Structure Algorithm

CSharp examples for Data Structure Algorithm:Sort

Description

Distribution Sort

Demo Code


using System.Linq;
using System.Collections.Generic;
using System;//from   w  w w.  j  av a2s .c o m

public class Main{
        /*       Distribution sort        */

        static public void Dist_Sort(int[] array) {

            int cnt = array.Length;
            int min = array.Min();
            int max = array.Max();

            int range = max - min + 1;
            var dict = new Dictionary<int, int>(range);

            for (int ii = 0; ii < cnt; ++ii) {

                var elem = array[ii];

                int count;
                if (!dict.TryGetValue(elem, out count))
                    count = 0;

                ++count;
                dict[elem] = count;


            }

            int position = 0;
            for (int ii = 0; ii < range; ++ii) {

                int count;
                if (!dict.TryGetValue(ii, out count))
                    continue;

                for (int jj = 0; jj < count; ++jj) {
                    array[position] = ii;
                    ++position;
                }

            }


        }
}

Related Tutorials