C++

What is std::sort() in C++ STL

Sorting is a necessary and useful task applied to data in daily life and Mathematics too. Usually, we want to sort numbers or objects in the required order, such as ascending order or descending order, or in odd series or even series. In C++ programming language, the Standard Template Library(TSL) includes built-in functions, methods, classes, iterators, algorithms, and data structures which make it more user-friendly.

The “sort()” is one of the most useful functions of STL that enables users to perform sorting operations. More specifically, it is used for sorting the range’s elements in increasing order as well as in decreasing order.

Quick Outline

Syntax of std::sort() in C++
Sort Algorithm in C++
How to Sort the Integer Array to Ascending Order(Default Sort) in C++?
How to Sort Integer Array to Decrementing Order in C++?
How to Sort Interval in C++ by Start Time?
Conclusion

Syntax of std::sort() in C++

The basic syntax of the “std::sort()” in C++ is:

void sort (RandomAccessIterator first, RandomAccessIterator second, Compare comp);

Here:

  • first”: the address of the array’s first element in the range to be sorted.
  • second”: the address of the array’s second element in the range to be sorted.
  • comp”: the comparison to be made with the array (optional argument)

Sort Algorithm in C++

Before moving ahead to get more knowledge about “sort()” in STL, we need to know some important points regarding the “sort()” function which are listed below:

  • The C++ STL contains a sort function that can be sorted in ascending or descending order.
  • Integral data type as well as the user-defined data can be sorted by using this function.
  • By default, it uses the quick sort, however, if it is not working fine and taking more time than required, it switches to the heap sort. In the case of a small-size array, it will switch to the insertion sort.
  • A parallel execution policy can be used for better performance.

How to Sort the Integer Array to Ascending Order (Default Sort) in C++?

The default behavior of the “sort()” function is sorting the set of items in ascending order when the “comp” argument is not passed. In the below-provided example, we have just passed the starting and ending parameters to sort an input array in ascending order:

#include <bits/stdc++.h>
using namespace std;

int main()
{
    int array1[] = {19, 21, 13, 6, 18, 20, 5, 1};
    int x = sizeof(array1) / sizeof(array1[0]);
        cout << "\n The Array Before Sorting: ";
    for (int y = 0; y < x; ++y)
        cout << array1[y] << " ";
        sort(array1, array1 + x);
    cout << "\nThe Sorted Array is: ";
    for (int y = 0; y< x; ++y)
        cout << array1[y] << " ";

    return 0;
}

Here:

  • First of all, we have added the “<bits/stdc++.h>” header file that contains every standard library.
  • Then, inside the “main()” function we declared the integer type array “array1[ ]” and initialized it with desired values.
  • Next, calculate the length of the input array and then save it. The “size(array1)” is the whole size of the array and the “size(array1[0])” is the size of a single array.
  • Afterward, we used the “for” loop and specified the loops starting, and ending points as well as the increment operator.
  • Finally, we used the “sort()” function and passed the starting point of the array and length “x” of the array up to which we needed the array to be sorted.
  • Lastly, print the output of the sorted array on the console using the “cout” stream.

Output

How to Sort Integer Type Array to Decrementing Order in C++?

In C++, we can also sort the integer array in descending order using the “sort()” function by adding its third parameter. Here, we sort the provided input data using the “std::greater<int>()” function inside the “sort()” function. It will compare the provided arguments and return “True” when the first one is greater than the other. It will return “False” if not matched. Let’s check the provided code block:

#include <bits/stdc++.h>
using namespace std;

int main()
{
    int array[] = {20, 2, 7, 6, 9, 11, 5, 1};
    int number = sizeof(array) / sizeof(array[0]);
    cout << "\n Array Before Sorting is: ";
    for (int i = 0; i < number; ++i)
        cout << array[i] << " ";
    sort(array, array + number, greater<int>());
        cout << "\nThe Sorted Array in Descending Order is: ";
        for (int i = 0; i < number; ++i)
            cout << array[i] << " ";

    return 0;
}

Here, we used the previously described example code and only passed the “greater<int>()” function within the “sort()” function as an argument. The resultant output is given below:

How to Sort Interval in C++ by Start Time?

To sort the intervals by start time in C++, users can customize their comparator function and add the customized function as a third parameter to the “sort()” in STL. The function will return a value that is convertible to bool, which indicates whether the provided first parameter must be placed before the passed second argument or not.

To understand the above-discussed concept in-depth, check out the following code block:

#include <bits/stdc++.h>
using namespace std;
struct timeInterval {
    int starting, ending;
};

bool compInter(timeInterval x1, timeInterval x2)
{
    return (x1.starting < x2.starting);
}

int main()
{
    timeInterval array[]
        = { { 2, 4 }, { 3, 6 }, { 1, 7 }, { 0, 5 } };
            int number = sizeof(array) / sizeof(array[0]);

    cout << "Intervals before sorted: ";
    for (int x = 0; x < number; x++)
        cout << "[" << array[x].starting << "," << array[x].ending
            << "] ";
        cout << "\n";

    sort(array, array + number, compInter);

    cout << "Sorted intervals by start time: ";
    for (int x = 0; x < number; x++)
        cout << "[" << array[x].starting << "," << array[x].ending
            << "] ";

    return 0;
}

Here:

  • First of all, we have added the required header files.
  • Then, specify the “starting” and “ending” integer type variables for time intervals.
  • Next, we used the bool type “comInter()” function for comparing the two intervals according to the starting times.
  • Afterward, we declared the “timeInterval” array[ ] and initialized it. Then, calculate the length of the input array and then save it. The “size(array1)” is the whole size of the array and the “size(array1[0])” is the size of a single array.
  • Next, sort the intervals in ascending order of the starting time by calling the “Sort” function.
  • Finally, showed the sorted array on the screen by using the output stream.

Output

You have learned detailed information about the “sort()” function in C++ STL.

Conclusion

Users want to sort numbers or objects in the required order, such as ascending order or descending order, or in odd series or even series. In C++ programming language, the “sort()” is one of the most efficient functions of STL that allows programmers to perform sorting operations. It is also used for sorting the range’s elements in increasing or decreasing order. In this guide, we have illustrated detailed information about the “sort()” function in C++ STL.

About the author

Maria Naz

I hold a master's degree in computer science. I am passionate about my work, exploring new technologies, learning programming languages, and I love to share my knowledge with the world.