# Why does a sorting algoritm require nested loops ?

• 09-29-2011
dantheman4
Why does a sorting algoritm require nested loops ?
thanks
• 09-29-2011
itsme86
If you can think of a more efficient way to sort without using nested loops, I'd be interested to hear it.
• 09-29-2011
itsme86
Also, you can avoid nested loops if you utilize recursion, but it just adds unnecessary complexity:
Code:

```    class Program     {         static void Main(string[] args)         {             int[] array = { 7, 2, 9, 8, 3, 4 };             Sort(array);             // Print the now sorted array             for (int i = 0; i < array.Length; ++i)                 Console.Write("{0} ", array[i]);             Console.WriteLine("");         }         private static void Sort(int[] array, int index = 0)         {             // Find the index (greater than or equal to the index passed in) with the smallest value             int smallest = index;             for (int i = index + 1; i < array.Length; ++i)                 if (array[i] < array[smallest])                     smallest = i;             // If the passed in index doesn't contain the smallest value, swap the values at the two indexes             if (smallest != index)             {                 int temp = array[smallest];                 array[smallest] = array[index];                 array[index] = temp;             }             // If we're not at the end of the array, sort the rest             if (index < array.Length)                 Sort(array, index + 1);         }     }```
Output...
Code:

```2 3 4 7 8 9 Press any key to continue . . .```