The part about
"... from least to most ..." made me think you were after a method to count the frequencies of the numbers and sort after those. Anyway I cooked up a generic solution that will do both sorts and dump them to the console:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SortNumbers
{
class Program
{
static void Main(string[] args)
{
Sorter<int>.RunTest(new int[] {
10, 3, 4, 10, 5, 3, 4, 10, 1, 2, 3, 5, 10, 8, 9, 9, 2, 4
});
Sorter<String>.RunTest(new String[] {
"This", "is", "a", "is", "test", "This", "a", "a", "a", "is", "test"
});
Console.ReadLine();
}
}
class Sorter<T> where T : IComparable
{
public T[] Matrix;
public static void RunTest(T[] matrix)
{
Sorter<T> test = new Sorter<T>();
test.Matrix = matrix;
T[] plain = test.SortPlain();
FrequencyNumber<T>[] frequ = test.SortByFrequency();
Sorter<T>.Dump(plain);
Sorter<T>.DumpFrequencies(frequ);
}
public T[] SortPlain()
{
T[] sorted = new T[Matrix.Length];
Array.Copy(Matrix, sorted, Matrix.Length);
Array.Sort(sorted);
return sorted;
}
public FrequencyNumber<T>[] SortByFrequency()
{
List<FrequencyNumber<T>> sorted = new List<FrequencyNumber<T>>();
foreach(T num in Matrix)
{
FrequencyNumber<T> toAdd = new FrequencyNumber<T>(num);
FrequencyNumber<T> inList = sorted.Find(delegate(FrequencyNumber<T> candidate)
{
return candidate.Equals(toAdd);
});
if (inList != null)
inList.Frequency++;
else
sorted.Add(toAdd);
}
sorted.Sort();
return sorted.ToArray<FrequencyNumber<T>>();
}
public static void Dump(T[] arr)
{
Console.WriteLine("\nPlain sorted!");
Console.WriteLine("-------------");
int idx = 0;
foreach (T elem in arr)
{
idx++;
Console.WriteLine("{0:###}. {1:########}", idx, elem);
}
}
public static void DumpFrequencies(FrequencyNumber<T>[] arr)
{
Console.WriteLine("\nFrequency sorted!");
Console.WriteLine("-------------");
int idx = 0;
foreach (FrequencyNumber<T> num in arr)
{
idx++;
Console.WriteLine(String.Format("{0:###}. Freq: {1:####} Number: {2:#######}", idx, num.Frequency, num.Number));
}
}
}
class FrequencyNumber<N> : IComparable where N : IComparable
{
public long Frequency;
public N Number;
public FrequencyNumber(N number)
{
Frequency = 1;
Number = number;
}
public int CompareTo(object obj)
{
if (obj != null && !(obj is FrequencyNumber<N>))
{
throw new ArgumentException(String.Format("Can't compare a {0} with a {1}", this.GetType(), obj.GetType()));
}
FrequencyNumber<N> num = (FrequencyNumber<N>)obj;
return Frequency.CompareTo(num.Frequency);
}
public bool Equals(object num)
{
if(num is FrequencyNumber<N>)
return this.Number.Equals(((FrequencyNumber<N>)num).Number);
else
return false;
}
}
}
If you have questions leave me a comment!
Tested in Visual Studio 2010, .NET 4.0.
Happy coding!
-MRB