0

I have some points like (g1, g2). I want to find median point by following formula:

median1

a naive solution is to use a nested loop but it's so inefficient for a large space (about 1 million points). does anyone know a linear time algorithm/code or near linear time for doing this in c++?

I implement the naive solution as following but it does not efficient for my problem:

vector<double> get_dists(unordered_map<string, label*> myGraph) {
    vector<double> sum_dists;
    for (unordered_map<string, label*>::iterator it = myGraph.begin(); it != myGraph.end(); it++) {
        double d = 0;
        for (unordered_map<string, label*>::iterator it2 = myGraph.begin(); it2 != myGraph.end(); it2++)
        {
            d += dist(it->second->num, it2->second->num)
        }
        sum_dists.push_back(d);
    }
    return sum_dists;
}

it return a vector of sum of distances and the it can use to get minimum element index.

xskxzr
  • 12,442
  • 12
  • 37
  • 77
FIFO
  • 41
  • 6
  • Show us what you've tried so far. – ShadowMitia Aug 11 '21 at 11:36
  • 1
    Pass collection by const reference instead of by value to avoid copies. – Jarod42 Aug 11 '21 at 11:44
  • I just updated the dist() function. can you explain more about pass by const in my code? Thank you @Jarod42 – FIFO Aug 11 '21 at 11:49
  • Well, doing some back of the envelope calculations, finding the median coordinates should be `O(n)`. Once this is found, then finding the point nearest the median point should also be `O(n)`, for the final complexity of `O(n)`? – Sam Varshavchik Aug 11 '21 at 11:50
  • I meant `get_dists(const std::unordered_map& myGraph)` – Jarod42 Aug 11 '21 at 12:17
  • Why does it say "median element index" in the title but your function is called "get dists"? In any case, is your question about C++ or the algorithm (which is language-agnostic)? – Ulrich Eckhardt Aug 12 '21 at 06:06
  • Thanks @Jarod42. it was very good hint but it does not solve my time efficiency problem about that. – FIFO Aug 12 '21 at 12:51
  • Isn't sorting element (by axis) allow to find median (or at least candidates). – Jarod42 Aug 12 '21 at 13:34

0 Answers0