Skip to content

Commit

Permalink
Make probe::dis O(n^2) instead of O(n^3) with some iterators
Browse files Browse the repository at this point in the history
probe::dis was accidentally O(n^3) with forward iterators and
bidirectional iterators. This commit changes the algorithm a bit to
avoid a lot of unnecessary calls to std::distance, and gives it its
marketed O(n^2) complexity for all categories of iterators.

Loosely related to issue #169.
  • Loading branch information
Morwenn committed Aug 27, 2020
1 parent 002c0e0 commit 2764e39
Showing 1 changed file with 9 additions and 13 deletions.
22 changes: 9 additions & 13 deletions include/cpp-sort/probes/dis.h
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2016-2017 Morwenn
* Copyright (c) 2016-2020 Morwenn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
Expand Down Expand Up @@ -62,24 +62,20 @@ namespace probe
auto&& comp = utility::as_function(compare);
auto&& proj = utility::as_function(projection);

if (first == last || std::next(first) == last)
{
if (first == last || std::next(first) == last) {
return 0;
}

difference_type max_dist = 0;
for (auto it1 = first ; it1 != last ; ++it1)
{
for (auto it1 = first ; it1 != last ; ++it1) {
auto&& value = proj(*it1);
for (auto it2 = std::next(it1) ; it2 != last ; ++it2)
{
if (comp(proj(*it2), value))
{
max_dist = std::max(
max_dist,
std::distance(it1, it2)
);

difference_type dist = 1; // Distance between it1 and it2
for (auto it2 = std::next(it1) ; it2 != last ; ++it2) {
if (comp(proj(*it2), value)) {
max_dist = std::max(max_dist, dist);
}
++dist;
}
}
return max_dist;
Expand Down

0 comments on commit 2764e39

Please sign in to comment.