[c++] sorting still using bubble sort? Learn about the sort function
Posted on Dec. 3, 2022, 9:12 a.m. by Sonya Reynolds
Category:
The back-end
Tag:
c++
The back-end
Sort function in C++
Bubble sort is inefficient, so it's not as good as using the simple sort function
Sort function
#include algorithm takes three arguments: sort (a,b,c) a: The first is the starting address of the array to be sorted. B: The second is the end address (the last bit of address to sort). C: The third parameter is the sorting method.
The following specific use of sort () function combination of array sort to do a description!
1. If there is no third argument, sort defaults to small to large
#includeiostream
#includealgorithm
using namespace std;
int main(a)
{
int a[10] = {9.6.3.8.5.2.7.4.1.0};
for(int i=0; i10; i++) couta[i]endl;sort(a,a+10);
for(int i=0; i10; i++) couta[i]endl;return 0;
}
Copy the code
2. The third argument to sort
Less data type () // Sort from smallest to largest
#includeiostream
#includealgorithm
using namespace std;
int main(a)
{
int a[10] = {9.6.3.8.5.2.7.4.1.0};
for(int i=0; i10; i++) couta[i]endl;sort(a,a+10,lessint ());for(int i=0; i10; i++) couta[i]endl;return 0;
}
Copy the code
Greater data type () // Sort from largest to smallest
#includeiostream
#includealgorithm
using namespace std;
int main(a)
{
int a[10] = {9.6.3.8.5.2.7.4.1.0};
for(int i=0; i10; i++) couta[i]endl;sort(a,a+10,greaterint ());for(int i=0; i10; i++) couta[i]endl;return 0;
}
Copy the code
3. Use the sort function to sort characters
#includeiostream
#includealgorithm
using namespace std;
int main(a)
{
char a[11] ="asdfghjklk";
for(int i=0; i10; i++) couta[i]endl;sort(a,a+10,greaterchar ());for(int i=0; i10; i++) couta[i]endl;return 0;
}
Copy the code