/**
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_ALGORITHM_HPP
#define REXY_ALGORITHM_HPP
#include "utility.hpp" //swap
#include //SIZE_MAX
#include //size_t
#include
#include "detail/algorithm.hpp"
namespace rexy{
//Requires Iterators to be LegacyRandomAccessIterators
//right is one past the end of the list
template
constexpr void quicksort(Iter left, Iter right, const Compare& cmp)
noexcept(noexcept(detail::qs_partition(left, right, cmp)))
{
while(left < right){
auto real_right = right-1;
auto pivot = detail::qs_partition(left, real_right, cmp);
quicksort(left, pivot, cmp);
left = ++pivot;
}
}
//Requires Iterators to be LegacyRandomAccessIterators
template
constexpr HIter two_way_search(const HIter& hstart, const HIter& hend, const NIter& nstart, const NIter& nend){
size_t j = 0;
size_t i = 0;
size_t nlen = nend - nstart;
size_t hlen = hend - hstart;
auto [suffix, period] = detail::critical_factorization(nstart, nend);
if(detail::iter_compare(nstart, nstart + period, suffix)){
size_t memory = SIZE_MAX;
while(j <= hlen - nlen){
i = max(suffix, memory) + 1;
//right side
while(i < nlen && nstart[i] == hstart[i + j]){
++i;
}
if(i >= nlen){
i = suffix;
//left side
while(i > memory && nstart[i] == hstart[i + j]){
--i;
}
if(i <= memory){
return hstart + j;
}
j += period;
memory = nlen - period - 1;
}else{
j += (i - suffix);
memory = SIZE_MAX;
}
}
}else{
period = max(suffix + 1, nlen - suffix - 1) + 1;
j = 0;
while(j <= hlen - nlen){
i = suffix + 1;
//right side
while(i < nlen && nstart[i] == hstart[i + j]){
++i;
}
if(i >= nlen){
i = suffix;
//left side
while(i != SIZE_MAX && nstart[i] == hstart[i + j]){
--i;
}
if(i == SIZE_MAX){
return hstart + j;
}
j += period;
}else{
j += (i - suffix);
}
}
}
return hend;
}
//searcher for use with generic search wrappers
struct two_way_searcher{
template
constexpr HIter operator()(const HIter& hstart, const HIter& hend, const NIter& nstart, const NIter& nend)const{
return two_way_search(hstart, hend, nstart, nend);
}
};
}
#endif