Simple Application Framework
1
|
00001 /* 00002 This file is part of Simple Application Framework (Saf) library. 00003 Copyright (C) 2010 - 2012 Ondrej Danek <ondrej.danek@gmail.com> 00004 00005 This library is free software: you can redistribute it and/or modify 00006 it under the terms of the GNU General Public License as published 00007 by the Free Software Foundation, either version 3 of the License, or 00008 (at your option) any later version. 00009 00010 Saf is distributed in the hope that it will be useful, 00011 but WITHOUT ANY WARRANTY; without even the implied warranty of 00012 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 00013 GNU General Public License for more details. 00014 00015 You should have received a copy of the GNU General Public License 00016 along with Simple Application Framework library. If not, 00017 see <http://www.gnu.org/licenses/>. 00018 */ 00019 00028 #ifndef SAF_ALGO_SORT_QUICKSORT_H 00029 #define SAF_ALGO_SORT_QUICKSORT_H 00030 00031 #include "../../Type.h" 00032 #include "../Predicate.h" 00033 #include "../../Collection/Pair.h" 00034 #include "SortInternal.h" 00035 00036 namespace Saf 00037 { 00038 namespace Algo 00039 { 00040 namespace Sort 00041 { 00059 template <class RanIter, class Pred> 00060 void QuickSort(RanIter begin, RanIter end, Pred pred) 00061 { 00062 while (Diff(end - begin) > 1) 00063 { 00064 // Find pivot and partition the sequence into two parts 00065 Collection::Pair<RanIter,RanIter> cut; 00066 cut = Internal::AlgoSort::PartitionSmart(begin, end, pred); 00067 00068 // Sort the shorter part first to achieve log(n) space complexity 00069 if (Diff(cut.m_first - begin) > Diff(end - cut.m_second)) 00070 { 00071 QuickSort(cut.m_second, end, pred); 00072 end = cut.m_first; 00073 } 00074 else 00075 { 00076 QuickSort(begin, cut.m_first, pred); 00077 begin = cut.m_second; 00078 } 00079 } 00080 } 00081 00098 template <class RanIter> 00099 void QuickSort(RanIter begin, RanIter end) 00100 { 00101 Predicate::Less<typename Type::IteratorTraits<RanIter>::ValType> pred; 00102 QuickSort(begin, end, pred); 00103 } 00104 } 00105 } 00106 } 00107 00108 #endif