Location>code7788 >text

Use of the sort algorithm

Popularity:431 ℃/2024-12-19 13:00:31

Use of the sort algorithm

As you can see, sort is a built-in sorting algorithm in the STL, which is underpinned by the use of multiple sorting algorithms in conjunction with each other.

  • Header files to include
#include<algorithm>
  • utilization
    sort(parameter1,parameter2,parameter3)
    Parameter 1: Iterator or address of the sorted left endpoints
    Parameter 2: Iterator or address of the right endpoint of the sort
    Parameter 3: Function to control sorting priority
    Attention:

Code Example:

  • Sorting an array
#include<iostream>
#include<algorithm>
using namespace std.
int main()
int main() = {
int a[100] = { 1,3,7,5,32,11,45,67 };
sort(a, a + 8); // note that it's a + 8 and not a + 7, the last bit after the last element, not the last element
for (int i = 0; i < 8; i++)
{
cout << a[i] << " ";
}
return 0;
}

  • Sorting a container as a vector.
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main()
{
	vector<int>arry;
	arry.push_back(4);
	arry.push_back(2);
	arry.push_back(23);
	arry.push_back(7);
	sort((), ());
	for (int i = 0; i < (); i++) {
		cout << arry[i] << " ";
	}
	return 0;
}

  • Write your own function to change the sorting priority, which will be from smallest to largest ---> from largest to smallest
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
bool cmp(int& a, int& b) {
	return a > b;
}
int main()
{
	vector<int>arry;
	arry.push_back(4);
	arry.push_back(2);
	arry.push_back(23);
	arry.push_back(7);
	sort((), (), cmp);
	for (int i = 0; i < (); i++) {
		cout << arry[i] << " ";
	}
	return 0;
}