Detailed explanation of C++ Sort function

Preface: sort()The function is <alogrithm>a function under the library. sort()The function is unstable. If you need a stable sorting algorithm, you can use it instead. The stable_sort()implementation stable_sortis based on merge sorting. Its time complexity is O(nlogn), which is generally faster than that based on Row sort()a little slower.

1. Two ways to call the sort function

Method 1 (default) void sort (RandomAccessIterator first, RandomAccessIterator last);
Method 2 (custom) void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);
  • Default: two parameters first, last, arrange the elements in the interval [first, last) in ascending order. [Note that the interval is left closed and right open]
  • Custom sorting: The user needs to specify the sorting rule Compare comp, and arrange the elements in the [first, last) interval according to the order specified by the user.

Example:

/*
Description:
jlh很喜欢吃水果,苹果是他最喜欢的,其次是梨。
他天天想着吃水果,竟然感动了女娲大神,
女娲大神给了他n个篮子,让他选择其中的m个(m<=n)个篮子。
每个篮子里有a个苹果和b个梨。请你们帮jlh选择篮子吧。
Input:
输入一个t(t<=10),表示有t组测试数据,
再输入n和m(0=<m<=n<=100000),
接下来的n行,输入a和b表示苹果和梨的数量。
Output:
按jlh选择的顺序
(先选苹果多的,苹果数量相同选梨多的,两者相同选序号小的)
篮子的序号(1-n),m个数用空格隔开。
Sample Input:
2
2 1
2 0
1 4

3 2
3 4
2 6
3 5
Sample Output:
1
3 1
 */
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstdio>
using namespace std;
/**
 * 自定义篮子
 */
class basket{
    
    
public:
    int apple;    // 苹果数量
    int pear;     // 梨的数量
    int id;       // id
};

/**
 * 自定义比较函数
 * @param a 篮子a
 * @param b 篮子b
 * @return
 * 若a,b中苹果数量不等,返回a, b 篮子中苹果数量;a>b返回true
 * 若a,b中梨的数量不等,返回a, b 篮子中梨数量;a>b返回true
 * 否则比较id小的篮子;a<b返回true
 */
bool compareFruitAlgorithm(const basket a, const  basket b) {
    
    
    if (a.apple != b.apple)
        return a.apple > b.apple;   // 若a,b中苹果数量不等,返回a, b 篮子中苹果数量;a>b返回true
    else if (a.pear != b.pear)
        return a.pear > b.pear;     // 若a,b中梨的数量不等,返回a, b 篮子中梨数量;a>b返回true
    else return a.id < b.id;            // 否则比较id小的篮子;a<b返回true
}

int main() {
    
    
    // Input:  输入一个t(t<=10),表示有t组测试数据,再输入n和m(0=<m<=n<=100000),接下来的n行,输入a和b表示苹果和梨的数量。
    // Output: 按jlh选择的顺序(先选苹果多的,苹果数量相同选梨多的,两者相同选序号小的)篮子的序号(1-n),m个数用空格隔开。
    int t;
    cin >> t;
    while(t--) {
    
        // while(0)就是false,便跳出循环。
        int n, m;   // 共有n个篮子,其中选m个篮子
        cin >> n >> m;
        vector<basket> baskets(n); // 建立n个篮子
        // 装入
        for (int i=0; i<n; ++i) {
    
    
            cin >> baskets[i].apple >> baskets[i].pear; // 装入苹果和梨的数量
            baskets[i].id=i+1;
        }

        // 排序
        sort(baskets.begin(), baskets.end(), compareFruitAlgorithm);
        //      vector.begin()就是指向第一个元素:[0]位置
        //      vector.end()指向最后一个元素的后一个元素位置。

        // 输出
        //      这里要注意,题目给的示例中,输出每一排最后一个元素之后是没有空格的,所以要分类讨论
        //          1.不是这一排最后一个要输出的元素,输出id之后再带上" ";
        //          2.是这一排最后一个元素,仅仅输出这个id,并且换行。
        for (int i=0; i<m; ++i) {
    
    
            if (i != m-1)
            	printf("%d ", baskets[i].id);   // 不是这一排最后一个要输出的元素,输出id之后再带上" "
            else printf("%d\n", baskets[i].id); // 是这一排最后一个元素,仅仅输出这个id,并且换行。
        }
    }
}

2. sort function usage scenarios

Since operations such as element exchange are involved in the sorting process, the sort function only supports randomly accessible containers, such as arrays, strings, vectors, deques, etc.

3. sort function sorting principle

​sort()Not just ordinary quick sort, in addition to optimizing ordinary quick sort, it also combines insertion sort and heap sort. According to different quantity levels and different situations, the appropriate sorting method can be automatically selected. When the amount of data is large, use quick sort and segment recursion. Once the amount of segmented data is less than a certain threshold, insertion sort will be used instead to avoid excessive additional load from recursive calls. And if the recursion level is too deep, there is a tendency for the worst case, and heap sorting will be used instead.

​So no matter what state the elements are in initially, sort()the average sorting complexity is equal O(nlog2(n)), which has good performance. When solving algorithm problems, you can directly use sort() to sort the data without manually writing the sorting function .

4. The custom comp function returns true or false

bool cmp(int num1, int num2) {
    
    	// 实现降序排列
    return num1 > num2;	// num1大于num2时返回true,否则返回false
}

The return value of the custom function is bool type

  • If it returns true, it means that num1 and num2 should exchange order;
  • If it returns false, then num1 and num2 keep the original order;

Guess you like

Origin blog.csdn.net/weixin_45827203/article/details/129686427