sorting numbers array question
I have a problem with arrays in c#. for example we have one array for store indexes (array length 0-99 ), one array for random generated numbers (array length 0-99) and array for frequencies (how many time numbers repeat).
Example
i: 0 1 2 3 4 ... i - index
n: 5 2 1 2 0 ... n - number f: 1 1 2 1 0 ... f - frequencyit is part of counting sort. And below we have another one example how I would like to sort without comulative computing
i: 0 1 2 3 4 ...
n: 5 2 1 2 0 ... f: 1 1开发者_开发知识库 2 1 0 ... s: 0 1 2 2 3 ... s - sorted-> frequency tell us how many 0,1,... are there and we only write it down
int[] arr = new int[100]; //generated numbers
int[] arr2 = new int[100]; //sorted array
int[] counter = new int[100]; //frequencies
//frequencies
for (int i = 0; i < st_el; i++)
{
counter[arr[i]] += 1;
}
for(int i=0; i<arr.length; i++)
{
for(int j=0; j<arr.length; j++)
{
//I do not know how to implement?
}
}
using LINQ you could do something like this:
var frequencies = numbers.GroupBy(n => n)
.Select(g => new { Number = g.Key, Frequency = g.Count() })
.ToList();
foreach (var item in frequencies)
{
Console.WriteLine("Number {0} occurs {1} times", item.Number, item.Frequency);
}
This will give you the frequency of each number in the numbers array - I think that's what you want.
Edit:
I think I understand now: You're up to the counting sort part itself - given the example you have only random numbers between 0 and 99 would be allowed, you only have to check every element of the count array to check the number of occurrences of the specific number, then repeat that number that many times (untested):
int index = 0;
for(int i=0; i< counter.length; i++)
{
for(j=index;j<index+counter[i];j++)
arr2[j] = i;
index+=counter[i];
}
I wouldn't use arrays at all. I hardly ever use them, especially given the (I assume) artificial limitations you have on array length.
Here is how I would handle it, asuming you are using at least .Net 3.5:
class Program
{
static void Main(string[] args)
{
var sorted = new List<int>();
var frequencies = new Dictionary<int, int>();
//Get a bunch of random numbers
var numbers = GetSomeRandomNumbers(100);
//Sort the numbers asscenting
foreach (var number in numbers.OrderBy(i => i))
{
//This will add the numbers in the expected order
sorted.Add(number);
//Frequencies is just a lookup table of number -> frequency
if (frequencies.ContainsKey(number))
frequencies[number]++;
else
frequencies.Add(number, 1);
}
Console.WriteLine("--SORTED--");
sorted.ForEach(number => Console.WriteLine(number));
Console.WriteLine("--FREQUENCIES--");
//Dump all of the frequencies as a quick test
frequencies.ToList().ForEach(pair => Console.WriteLine(string.Format("{0} occurrences of {1}", pair.Value, pair.Key)));
//Wiat
Console.ReadLine();
}
private static List<int> GetSomeRandomNumbers(int count)
{
var random = new Random();
var result = new List<int>();
for (int i = 0; i < count; i++)
result.Add(random.Next(0, 100));
return result;
}
}
精彩评论