简体   繁体   English

带有自定义比较器 function 的 C++ 中 sort() 的时间和空间复杂度是多少?

[英]What is the Time and space complexity of sort() in C++ with custom comparator function?

Consider the following code-考虑以下代码 -

 bool cmp(pair<string,int> &a, pair<string,int> &b) {
     return ((a.second > b.second) || (a.second==b.second && a.first<b.first));
 }

vector<pair<string,int>> v;

sort(v.begin(),v.end(),cmp);

For this case, what would be my complexity?对于这种情况,我的复杂性是多少? Will it be O(nlogn) ?会是O(nlogn)吗?

std::sort has time complexity: O(NlogN) custom comparisons . std::sort具有时间复杂度: O(NlogN) custom comparisons
But in your case the comparator function cmp also performs string comparison ,但在您的情况下,比较器 function cmp也执行字符串比较

(a.second==b.second && a.first<b.first) (a.second==b.second && a.first<b.first)

std::basic_string operator< has time complexity linear in the size of the strings. std::basic_string operator<具有与字符串大小成线性关系的时间复杂度。

Hence, worst case complexity is O(K*NlogN) char comparisons , where K is length of the string.因此,最坏情况的复杂度是O(K*NlogN) 字符比较,其中 K 是字符串的长度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM