排序函數(shù)
1.std::sort (不穩(wěn)定排序,時(shí)間復(fù)雜度為O(n log n))
std::vector<int> list; std::sort(list.begin(),list.end()); // 默認(rèn)升序 std::less<int>(); std::sort(list.begin(),list.end(),std::greater<int>()); // 降序 auto cmp = [](int x,int y){return x<y;}; std::sort(list.begin(),sort.end(),cmp); // 自定義比較函數(shù)
2.std::stable_sort(穩(wěn)定排序,時(shí)間復(fù)雜度為O(n log n),排序時(shí)有相同的比較值元素,可以保證每次排序結(jié)果一致,代價(jià)是額外的空間復(fù)雜度)
1 struct Obj 2 { 3 int index=0; 4 std::string name; 5 } 6 7 std::vector<Obj> objects; 8 objects.emplace_back(2,"test2"); 9 objects.emplace_back(2,"test3"); 10 objects.emplace_back(3,"test4"); 11 12 std::stable_sort(objects.begin(),objects.end(),[](const auto &obj1,const auto &obj2){return obj1.index < obj2.index;}):
3.std::partial_sort(部分排序,時(shí)間復(fù)雜度為O(n log n),不穩(wěn)定排序)

浙公網(wǎng)安備 33010602011771號(hào)