5 // Alejandro Serrano "Serras" (trupill@yahoo.es)
6 // Marek Safar <marek.safar@gmail.com>
7 // Jb Evain (jbevain@novell.com)
9 // (C) 2007 - 2008 Novell, Inc. (http://www.novell.com)
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
32 using System.Collections.Generic;
34 namespace System.Linq {
36 class QuickSort<TElement> {
40 SortContext<TElement> context;
42 QuickSort (IEnumerable<TElement> source, SortContext<TElement> context)
44 this.elements = source.ToArray ();
45 this.indexes = CreateIndexes (elements.Length);
46 this.context = context;
49 static int [] CreateIndexes (int length)
51 var indexes = new int [length];
52 for (int i = 0; i < length; i++)
60 // If the source contains just zero or one element, there's no need to sort
61 if (elements.Length <= 1)
64 context.Initialize (elements);
66 // Then sorts the elements according to the collected
67 // key values and the selected ordering
68 Array.Sort<int> (indexes, context);
71 public static IEnumerable<TElement> Sort (IEnumerable<TElement> source, SortContext<TElement> context)
73 var sorter = new QuickSort<TElement> (source, context);
75 sorter.PerformSort ();
77 for (int i = 0; i < sorter.elements.Length; i++)
78 yield return sorter.elements [sorter.indexes [i]];