[C++STL] The principle and use of quick sort algorithm (sort)

1. sortAlgorithm Principle

std::sortIt is a sorting algorithm provided in the C++ standard library. It uses a classic sorting algorithm - Quicksort (Quicksort) or a variant thereof.

Quick sort is a sorting algorithm based on comparison. By continuously selecting a pivot value, the sequence to be sorted is divided into two subsequences. All elements of one subsequence are less than or equal to the pivot value, and all elements of the other subsequence are less than or equal to the pivot value. The element is greater than the base value. The two subsequences are then sorted recursively, finally resulting in an ordered sequence.

std::sortWhen implementing quick sort, other optimization techniques, such as insertion sort or heap sort, are usually combined to improve the performance and efficiency of the algorithm.

Basic steps for quick sort:

  1. Choose a pivot value. You can select the first element, the last element, the middle element of the sequence, or a random element as the base value.
  2. Split the sequence into two subsequences, so that all elements of one subsequence are less than or equal to the benchmark value, and all elements of the other subsequence are greater than the benchmark value.
  3. Sort two subsequences recursively, that is, sort the subsequences that are less than or equal to the reference value and the subsequences that are greater than the reference value.
  4. Merge the two sorted subsequences to obtain the final ordered sequence.

Quick sort is an in-place sorting algorithm whose average time complexity is O(nlogn), where n is the size of the sequence to be sorted. In the worst case, the time complexity of quick sort is O(n^2), but the probability of the worst case can be reduced by rationally selecting the benchmark value.

std::sortThe implementation takes into account performance and efficiency in different situations, and may vary across different compilers and library implementations. It usually selects an appropriate sorting algorithm based on the size of the sequence, data type, and other factors to achieve better performance. For small sequences, std::sortinsertion sort or other simple sorting algorithms may be used, while for large sequences, it usually uses quick sort or a variant thereof. In addition, std::sortcustom comparison functions or predicates can be accepted to meet different sorting needs.

2. sortAlgorithm use

Function: Arrange the elements in the container (default in ascending order)

  • sort()Belongs to qualitative change algorithm
Function prototype: sort(iterator beg, iterator end, pred) explain
Parameter 1 iterator beg start iterator
Parameter 2 iterator end end iterator
Parameter 3 before predicate

details:

When called std::sortto sort, it uses a divide-and-conquer quicksort algorithm, which means that it splits the elements to be sorted into smaller subsets, then sorts these subsets and gradually merges them, finally getting Fully sorted results.

  • Sorting range:std::sort Sorting is a range, specified by two iterators firstand last, indicating the starting position and ending position of sorting. Sorting will be applied to [first, last)elements within the range.
  • Sorting criteria: By default, comparisons std::sortusing <the operator are used to determine the order of elements. If you want to sort by other criteria, you can provide a custom comparison function or function object as the optional third argument. This comparison function or function object should accept two arguments and return a Boolean value indicating whether the first argument should come before the second argument in sorting.
  • Time complexity:std::sort Using the quick sort algorithm, its average time complexity is O(n log n), where n is the number of elements to be sorted. In the worst case, quicksort has a time complexity of O(n^2), but this rarely happens.
  • Container requirements:std::sort Can be used for standard containers (such as std::vector, std::deque, std::listetc.) and ordinary arrays. Sorting is performed in place, that is, the order of elements in the container is directly modified without creating a new container.
  • Customizable types:std::sort Not only basic types (such as integers, floating point numbers) can be sorted, but also custom types can be sorted, as long as the custom type supports comparison operators <or provides custom comparison functions.
  • Iterator invalidation:std::sort Iterators are not invalidated, meaning that the original container's iterators can still be used after sorting.
  • Stability:std::sort The stability of the sort is not guaranteed, that is, the order of equal elements may change after sorting. If you need to keep the order of equal elements unchanged, you can use std::stable_sortthe algorithm.

Example 1: Sort in ascending order by default

#include <iostream>
#include <algorithm> //必须包含该头文件
#include <vector>
using namespace std;

//函数对象(仿函数)
class print
{
    
    
public:
	void operator()(int value)
	{
    
    
		cout << value << " ";
	}
};

void test01()
{
    
    
	vector<int> vec = {
    
    6, 9, 3, 4, 2, 7, 1, 5, 8};

	//排序前
	cout << "排序前:";
	for_each(vec.begin(), vec.end(), print());
	cout << endl;

	//排序后-升序
	cout << "排序后:";
	sort(vec.begin(), vec.end());   //默认升序
	for_each(vec.begin(), vec.end(), print());
	cout << endl;
}

int main()
{
    
    
	test01();
	system("pause");
	return 0;
}
//result
排序前:6 9 3 4 2 7 1 5 8
排序后:1 2 3 4 5 6 7 8 9

Example 2: Using predicatesstd::greater<>

  • greater<>Is a template class, which is a binary predicate (binary predicate), used to compare the size relationship between two values.
#include <iostream>
#include <algorithm> //必须包含该头文件
#include <vector>
using namespace std;

//函数对象(仿函数)
class print
{
    
    
public:
	void operator()(int value)
	{
    
    
		cout << value << " ";
	}
};

void test01()
{
    
    
	vector<int> vec = {
    
    6, 9, 3, 4, 2, 7, 1, 5, 8};

	//排序前
	cout << "排序前:";
	for_each(vec.begin(), vec.end(), print());
	cout << endl;

	//排序后-降序-添加谓词greater
	cout << "排序后:";
	sort(vec.begin(), vec.end(), greater<int>());
	for_each(vec.begin(), vec.end(), print());
	cout << endl;
}

int main()
{
    
    
	test01();
	system("pause");
	return 0;
}
//result
排序前:6 9 3 4 2 7 1 5 8
排序后:9 8 7 6 5 4 3 2 1

Example 3: Custom type sorting

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

class goods
{
    
    
public:
    goods(string name, int price)
    {
    
    
        m_name = name;
        m_price = price;
    }

public:
    string m_name;
    int m_price;
};

// 自定义排序-根据商品价格升序
struct arrange
{
    
    
    bool operator()(const goods& value1, const goods& value2)
    {
    
    
        return value1.m_price < value2.m_price;
    }
};

class print
{
    
    
public:
    void operator()(const goods& value)
    {
    
    
        cout << "名称:" << value.m_name  << "\t价格:" << value.m_price << endl;
    }
};

void test01()
{
    
    
    goods goods1("可乐", 3);
    goods goods2("红牛", 5);
    goods goods3("脉动", 4);
    goods goods4("外星人", 6);
    goods goods5("雪碧", 3);
    goods goods6("哇哈哈", 2);

    vector<goods> vec;
    vec.push_back(goods1);
    vec.push_back(goods2);
    vec.push_back(goods3);
    vec.push_back(goods4);
    vec.push_back(goods5);
    vec.push_back(goods6);

    // 排序前
    cout << "排序前:" << endl;
    for_each(vec.begin(), vec.end(), print());
    cout << endl;

    // 排序后-升序-添加谓词arrange
    cout << "排序后:" << endl;
    sort(vec.begin(), vec.end(), arrange());
    for_each(vec.begin(), vec.end(), print());
    cout << endl;
}

int main()
{
    
    
    test01();
    system("pause");
    return 0;
}
//result
排序前:
名称:可乐      价格:3
名称:红牛      价格:5
名称:脉动      价格:4
名称:外星人    价格:6
名称:雪碧      价格:3
名称:哇哈哈    价格:2

排序后:
名称:哇哈哈    价格:2
名称:可乐      价格:3
名称:雪碧      价格:3
名称:脉动      价格:4
名称:红牛      价格:5
名称:外星人    价格:6

Summary:std::sort It is an efficient, versatile and flexible sorting algorithm. It provides good performance in most cases and can be applied to different types of containers and custom types. However, for some special needs, such as the need for stable sorting or sorting large containers, it may be necessary to choose another sorting algorithm or use a custom sorting implementation.


If this article is helpful to you, I would like to receive a like from you!

Insert image description here

Guess you like

Origin blog.csdn.net/AAADiao/article/details/131011879
Recommended