1 // Created on: 2011-01-27
3 // Copyright (c) 2011-2014 OPEN CASCADE SAS
5 // This file is part of Open CASCADE Technology software library.
7 // This library is free software; you can redistribute it and/or modify it under
8 // the terms of the GNU Lesser General Public License version 2.1 as published
9 // by the Free Software Foundation, with special exception defined in the file
10 // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
11 // distribution for complete text of the license and disclaimer of any warranty.
13 // Alternatively, this file may be used under the terms of Open CASCADE
14 // commercial license or contractual agreement.
16 #ifndef _NCollection_QuickSort_HeaderFile
17 #define _NCollection_QuickSort_HeaderFile
19 #include <NCollection_Comparator.hxx>
20 #include <Standard_Integer.hxx>
23 * Perform sorting of enumerable collection with QuickSort algorithm.
24 * Enumerable collection should provide the random access to its values
25 * by index number with methods Value(theId) and ChangeValue(theId).
26 * Currently it supposed to be used with NCollection_Sequence and NCollection_Vector.
30 * NCollection_Sequence<Standard_Real> aSequence;
31 * // perform sorting for the whole sequence.
32 * NCollection_QuickSort<NCollection_Sequence<Standard_Real>, Standard_Real>
33 * ::Perform (aSequence, NCollection_Comparator<Standard_Real>(),
34 * 1, aSequence.Size());
36 template<class TheCollType, class TheItemType>
37 class NCollection_QuickSort
41 //! Main entry call to perform sorting
42 static void Perform (TheCollType& theEnumColl,
43 const NCollection_Comparator<TheItemType>& theComparator,
44 const Standard_Integer theLower,
45 const Standard_Integer theUpper)
47 if (theLower < theUpper)
49 Standard_Integer aPivotPosition = Partition (theEnumColl, theComparator,
51 if (theLower < aPivotPosition)
54 Perform (theEnumColl, theComparator,
55 theLower, aPivotPosition - 1);
58 Perform (theEnumColl, theComparator,
59 aPivotPosition + 1, theUpper);
65 //! Auxiliary function
66 static void SwapValues (TheItemType& x, TheItemType& y)
68 TheItemType aCopy = x;
73 static Standard_Integer Partition (TheCollType& theEnumColl,
74 const NCollection_Comparator<TheItemType>& theComparator,
75 const Standard_Integer theLower,
76 const Standard_Integer theUpper)
78 Standard_Integer anIdLeft (theLower), anIdRight (theUpper);
79 const TheItemType aPivot = theEnumColl.Value (theLower);
81 while (anIdLeft < anIdRight)
83 while (theComparator.IsGreater (theEnumColl.Value (anIdRight), aPivot))
87 while ((anIdLeft < anIdRight) &&
88 theComparator.IsLowerEqual (theEnumColl.Value (anIdLeft), aPivot))
93 if (anIdLeft < anIdRight)
95 SwapValues (theEnumColl.ChangeValue (anIdLeft),
96 theEnumColl.ChangeValue (anIdRight));
100 theEnumColl.ChangeValue (theLower) = theEnumColl.Value (anIdRight);
101 theEnumColl.ChangeValue (anIdRight) = aPivot;
107 #endif /*_NCollection_QuickSort_HeaderFile*/