# Sorting an Array

• 06-28-2012
Mcdom34
Sorting an Array
Hello, I am trying to sort an array of random numbers by passing it to a method Sort(), sort the array, and then pass the entire array back to the calling program. Each time I run this though, the array doesn't seem to sort. I'm not sure if the problem lies with my sorting algorithm or if it has something to do with calling the function.
Code:

```static void HighAverage(int[] a)        {             for (int i = 0; i < a.Length; i++)             {                 if ((i + 1) % 10 == 0 && i != 0)                     Console.WriteLine(a[i]);                 else                     Console.Write("{0} ", a[i]);             }             Console.WriteLine("\n");             Sort(ref a);             for (int i = 0; i < a.Length; i++)             {                 if ((i + 1) % 10 == 0 && i != 0)                     Console.WriteLine(a[i]);                 else                     Console.Write("{0} ", a[i]);             }         }         static void Sort(ref int[] a)         {             int min, t;             for (int i = 0; i < a.Length - 1; i++)             {                 min = i;                 for (int j = (i + 1); j < a.Length; j++)                 {                     if (a[j] < a[min])                         min = j;                 }                 t = a[min]; a[min] = a[i]; a[i] = a[min];             }         }```
• 06-28-2012
std10093
in line 32 variable t is not used properly.You should write a[i] = t; at the end of the line :)
• 06-28-2012
Mcdom34
Thanks! It works perfectly now :tongue:
• 06-28-2012
std10093
I am glad to here that.However notice that if the lenght of the array is large,then the complexity of this algorithm will be Θ(nē),which is very bad.
• 06-28-2012
Mcdom34
If that were the case, what would you suggest I do instead of using selection sort?
• 06-28-2012
VirtualAce
There is a much simpler and more elegant way to do this. It just so happens the MSDN example uses temperatures.
IComparable Interface (System)

Object oriented languages are all about objects. Primitive arrays and the like should be avoided wherever possible. There are generally better constructs available for representing the data.