/**
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 .
*/
#ifndef REXY_CX_ALGORITHM_HPP
#define REXY_CX_ALGORITHM_HPP
#include "utility.hpp" //swap
#include
namespace rexy::cx{
template
constexpr Iter qs_partition(Iter left, Iter right, const Compare& cmp)
noexcept(std::is_nothrow_invocable::value &&
noexcept(cx::swap(*left,*right)))
{
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
constexpr void quicksort(Iter left, Iter right, const Compare& cmp)
noexcept(noexcept(cx::qs_partition(left, right, cmp)))
{
while(left < right){
auto real_right = right-1;
auto pivot = qs_partition(left, real_right, cmp);
quicksort(left, pivot, cmp);
left = ++pivot;
}
}
}
#endif