Skip to content
Snippets Groups Projects
Commit ad77893c authored by Dmitri Naumov's avatar Dmitri Naumov Committed by Tom Fischer
Browse files

[BL] Generalize quicksort to use a give comparator

parent 70d3573b
No related branches found
No related tags found
No related merge requests found
...@@ -19,11 +19,10 @@ ...@@ -19,11 +19,10 @@
namespace BaseLib namespace BaseLib
{ {
/// @pre {first1 <= last1 and the second iterator can be incremented /// @pre {first1 <= last1 and the second iterator can be incremented
/// distance(first1, last1) times} /// distance(first1, last1) times}
template <typename It1, typename It2> template <typename It1, typename It2, typename Comparator>
void quicksort(It1 first1, It1 last1, It2 first2) void quicksort(It1 first1, It1 last1, It2 first2, Comparator compare)
{ {
using T1 = typename std::iterator_traits<It1>::value_type; using T1 = typename std::iterator_traits<It1>::value_type;
using T2 = typename std::iterator_traits<It2>::value_type; using T2 = typename std::iterator_traits<It2>::value_type;
...@@ -35,10 +34,7 @@ void quicksort(It1 first1, It1 last1, It2 first2) ...@@ -35,10 +34,7 @@ void quicksort(It1 first1, It1 last1, It2 first2)
[](T1 const& t1, T2 const& t2) { return std::make_pair(t1, t2); }); [](T1 const& t1, T2 const& t2) { return std::make_pair(t1, t2); });
// Sort data using first element of the pair. // Sort data using first element of the pair.
std::sort(begin(data), end(data), std::sort(begin(data), end(data), compare);
[](std::pair<T1, T2> const& a, std::pair<T1, T2> const& b) {
return (a.first < b.first);
});
// Unzip sorted data. // Unzip sorted data.
for (auto const& pair : data) for (auto const& pair : data)
...@@ -49,6 +45,19 @@ void quicksort(It1 first1, It1 last1, It2 first2) ...@@ -49,6 +45,19 @@ void quicksort(It1 first1, It1 last1, It2 first2)
++first2; ++first2;
} }
} }
/// @pre {first1 <= last1 and the second iterator can be incremented
/// distance(first1, last1) times}
template <typename It1, typename It2>
void quicksort(It1 first1, It1 last1, It2 first2)
{
using T1 = typename std::iterator_traits<It1>::value_type;
using T2 = typename std::iterator_traits<It2>::value_type;
quicksort(first1, last1, first2,
[](std::pair<T1, T2> const& a, std::pair<T1, T2> const& b) {
return a.first < b.first;
});
}
/// @pre {end<=array.size() and perm.size()==array.size()} /// @pre {end<=array.size() and perm.size()==array.size()}
template <typename T1, typename T2 = std::size_t> template <typename T1, typename T2 = std::size_t>
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment