thanks
This is a discussion on Why does a sorting algoritm require nested loops ? within the Tech Board forums, part of the Community Boards category; thanks...
thanks
If you can think of a more efficient way to sort without using nested loops, I'd be interested to hear it.
If you understand what you're doing, you're not learning anything.
Also, you can avoid nested loops if you utilize recursion, but it just adds unnecessary complexity:
Output...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); } }
Code:2 3 4 7 8 9 Press any key to continue . . .
Last edited by itsme86; 09-29-2011 at 12:38 PM.
If you understand what you're doing, you're not learning anything.