You can use built-in Sort method
// Declare an array with ten elements
//int[] a = new int[20];
int[] a = new int[10];
Random rand = new Random();
for (int i = 0; i < 10; i++) a[i] = rand.Next(10000);
for (int i = 0; i < 10; i++) Console.WriteLine(a[i]);
// Sort array
Array.Sort(a);
// Dump values
for (int i = 0; i < 10; i++) Console.WriteLine(a[i]);
Console.Read();
Now it's important not to declare too "big" array because elements have the default value 0 and they would be sorted too :)
HTH
Teme64
Veteran Poster
1,031 posts since Aug 2008
Reputation Points: 218
Solved Threads: 203
If I understand you, you want to get 20 different numbers (or what ever) using a Random class. If you will only use random.Next method, it possible of duplications too you know.
Ok, next thing, you have to show all 20 numbers in the order they were inserted into an array, and the same 20 numbers sorted.
So lets do this code:
Random r = new Random();
int[] array = new int[20];
for(int i = 0; i < array.Lenght; i++)
{
while(true)
{
int num = r.Next(1, 10001);
if(!array.Contains(num)
{
array[i] = num;
break;
}
}
}
Console.WriteLine("Unsorted numbers are: {0}.", String.Join(",", array.Select(s => s.ToString()).ToArray()));
Array.Sort(array); //sorting array!
Console.WriteLine("Sorted numbers are: {0}.", String.Join(",", array.Select(s => s.ToString()).ToArray()));
Last part is using Linq, to display an array, using Join method. Inside of it I used a Linq (lambda expressions) to join numbers, which must be strings it you want to use Join method).
Not big deal.
Mitja Bonca
Nearly a Posting Maven
2,485 posts since May 2009
Reputation Points: 641
Solved Threads: 474