Think of sorting every day, bubble, binary search, and the result comes with the sorting function sort and qsort in STL, finally saving yourself ~
So I summarized it myself. First, the sort function is shown in the following table:
Function Name |
Function Description |
Sort |
Sorts all elements in a given range. |
Stable_sort |
Performs a stable sorting of all elements in a given range. |
Partial_sort |
Sorts all elements in a given range. |
Partial_sort_copy |
Copy and sort a given interval |
Nth_element |
Find the elements corresponding to a location in a given range |
Is_sorted |
Determine whether the order of an interval has been sorted |
Partition |
Place elements that meet certain conditions in front of them. |
Stable_partition |
Relatively stable putting elements that meet certain conditions in front |
To use this function, you only need to use # include <algorithm> sort. The syntax is described as follows:
Sort (begin, end) indicates a range, for example:
Int _ tmain (INT argc, _ tchar * argv [])
{
Int A [20] = {, 76, 24, 65}, I;
For (I = 0; I <20; I ++)
Cout <A [I] <Endl;
Sort (A, A + 20 );
For (I = 0; I <20; I ++)
Cout <A [I] <Endl;
Return 0;
}
The output result will sort array a in ascending order. Someone may ask how to sort array a in descending order? This is the content of the next discussion.
Compile a comparison function and call the sort: Sort (begin, end, compare) of the three parameters. This method also applies to list containers. You can use compare as the sort parameter, that is, sort (compare ).
Compile the Compare function by yourself:
Bool compare (int A, int B)
{
Return a <B; // ascending order. If it is changed to return A> B, it is in descending order.
}
Int _ tmain (INT argc, _ tchar * argv [])
{
Int A [20] = {, 76, 24, 65}, I;
For (I = 0; I <20; I ++)
Cout <A [I] <Endl;
Sort (A, A + 20, compare );
For (I = 0; I <20; I ++)
Cout <A [I] <Endl;
Return 0;
}