-3

I am trying to write a sorting algorithm for the following unordered map. I have seen this question and I am trying to implement it for an unordered map, but it is not working!

Note- I am not allowed to use any STL sort functions.

void quickSort(unordered_map<string, int> map, unordered_map<string, int>::iterator left,unordered_map<string, int>::iterator right) {

    unordered_map<string, int>::iterator i=left;
    unordered_map<string, int>::iterator j=right;
    unordered_map<string, int>::iterator pivot = std::advance(map.begin(), map.size() / 2);

    unordered_map<string, int> tmp;
}

int main(){
    unordered_map<string, int> map;
    map["blah"] = 2;
    map["the"] = 5;
    quickSort(map,map.begin(),map.end());
}
Community
  • 1
  • 1
Bernard
  • 4,240
  • 18
  • 55
  • 88

2 Answers2

2

An unordered map does not have order(as its name implies) and thus finding the median in an unordered map does not make sense. If you need to find the median - use a auxiliary array and perform some implementation of nth_element algorithm in it. This step would be with linear complexity.

Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176
2

As stated in the comments, you cannot sort a unordered_map in place because its value_type is std::pair<const Key, T> (note the const!) for an unordered_map<Key,T>. This means that you cannot swap elements in the map, so you cannot sort it. You will need to copy the data into another data-structure like a vector, then you can use some "home-grown" version of std::nth_element on it:

std::vector<std::pair<Key,T>> med {map.begin(), map.end()};
my_nth_element(med.begin(), med.end(), med.begin() + med.size() / 2);
auto median = med[med.size()/2];

You should implement your nth_element with linear complexity on average. (If the number of input values happens to be even, you need to use the mean of both middle-values.)

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182