rexylib/include/rexy/cx/algorithm.hpp

57 lines
1.6 KiB
C++

/**
This file is a part of rexy's general purpose library
Copyright (C) 2020 rexy712
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef REXY_CX_ALGORITHM_HPP
#define REXY_CX_ALGORITHM_HPP
#include "utility.hpp" //swap
namespace rexy::cx{
template<class Iter, class Compare>
constexpr Iter qs_partition(Iter left, Iter right, const Compare& cmp){
auto range = right - left;
auto pivot = left + (range / 2);
auto value = *pivot;
//move pivot value all the way to the right side to preserve it
cx::swap(*pivot, *right);
for(auto it = left;it != right;++it){
if(cmp(*it, value)){
cx::swap(*left, *it);
++left;
}
}
//move pivot value back to proper position
cx::swap(*left, *right);
return left;
}
template<class Iter, class Compare>
constexpr void quicksort(Iter left, Iter right, const Compare& cmp){
while(left < right){
auto real_right = right-1;
auto pivot = qs_partition(left, real_right, cmp);
quicksort(left, pivot, cmp);
left = ++pivot;
}
}
}
#endif