Last Updated on April 20, 2023 by Prepbytes
Sorting is a fundamental operation in computer science and programming, and C++ provides a built-in sort function that can be used to sort various types of data structures such as arrays, vectors, and lists. Let us learn about the sort Function in C++ in detail with help of examples.
C++ Sort Function
The sort Function in C++ is used to sort the data structures such as arrays, vectors, lists, etc. The sort function in C++ is included in the STL library of C++. In order to utilize the sort function in our code, we must include the algorithm library by adding the line #include < algorithm>.
Syntax of sort() Function in C++
The syntax of the sort Function in C++ is given below.
default (1)
template
void sort (RandomAccessIterator first, RandomAccessIterator last);
custom (2)
template
void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);
// custom(2) for sorting in descending order
template
void sort (RandomAccessIterator first, RandomAccessIterator last, greater());
Parameters of sort() Function
The sort Function in C++ has the following three parameters.
- first: This parameter is RandomAccessIterator that is pointing to the first element in the range to be sorted. This element is inclusive in the range for sorting.
- last: This is also a RandomAccessIterator which points to the last element in the range for sorting and this last element is not included in the range for sorting.
- comp: This parameter is an optional parameter that is used to specify the comparison function to be used for sorting. If this parameter is not provided, the elements will be sorted in ascending order.
- greater< data_type>: This parameter is used to sort the array or a vector of given data_type in descending order.
Return Type of sort() Function in C++
The sort Function in C++ does not return anything. Its return type is void.
Time Complexity of sort() Function in C++
The time complexity of the sort Function in C++ is N * log2N, where N is the size of the data structure passed.
Exceptions of sort() Function in C++
The sort() function in C++ can throw an exception if any of the element comparisons, the element swap, or an operation on the iterator throws an exception.
Internal Working of sort() Function in C++
The sort() function in C++ is implemented using a sorting algorithm known as Introsort. Introsort is a hybrid sorting algorithm that combines the advantages of Quicksort, Heapsort, and Insertion sort. The basic idea behind Introsort is to use Quicksort initially to quickly sort the data set. Quicksort’s worst-case time complexity is O(n^2), which can occur when the partitioning is unbalanced. To avoid the worst-case scenario, Introsort switches to Heapsort. Also, Introsort switches to Insertion sort for very small data sets. Insertion sort is an efficient sorting algorithm for small data sets,
Examples of sort() Function in C++
Let us learn how to use the sort Function in C++ with the help of the following examples.
Example 1 of sort() Function in C++: Sorting an Array
To sort an array using the sort function in C++, we need to pass the starting and ending addresses of the array to the sort function in C++.
Code:
#include <iostream> #include <algorithm> using namespace std; int main() { int arr[] = {5, 2, 7, 3, 1}; int n = sizeof(arr)/sizeof(arr[0]); cout<<"Initial Array: "; for (int i = 0; i < n; i++) { cout << arr[i] << " "; } cout<<endl; sort(arr, arr + n); cout<<"Array after sorting: "; for (int i = 0; i < n; i++) { cout << arr[i] << " "; } return 0; }
Output:
Initial Array: 5 2 7 3 1
Array after sorting: 1 2 3 5 7
Explanation:
In this code, first, we initialized an array with some values. Then we use the sort Function in C++ to sort the array. We passed the address of the first element i.e, arr, and the last element of the array i.e., arr+n. Then we printed the sorted array on the console.
Example 2 of sort() Function in C++: Sorting a Vector
Let us now sort a vector using the sort Function in C++.
Code:
#include <iostream> #include <algorithm> #include <vector> using namespace std; int main() { vector<int> vec = {5, 2, 7, 3, 1}; sort(vec.begin(), vec.end()); for (int i = 0; i < vec.size(); i++) { cout << vec[i] << " "; } return 0; }
Output:
1 2 3 5 7
Explanation:
In this example, we create a vector vec of size 5 and initialize it with some values. We pass the starting iterator of the vector (vec.begin()) and the ending iterator of the vector (vec.end()) to the sort function. After sorting the vector, we use a for loop to print the sorted elements on the screen.
Example 3 of sort() Function in C++: Sorting Array of Strings in Descending Order
The given example shows how can use the greater< data_type> parameter to sort the array of strings in descending order.
Code:
#include <iostream> #include <algorithm> #include <string> using namespace std; int main() { int n = 5; string myarray[] = {"apple", "banana", "orange", "pear", "grape"}; sort(myarray, myarray + n, greater<string>()); for (auto it = myarray; it != myarray + n; ++it) { cout << *it << " "; } return 0; }
Output:
pear orange grape banana apple
Explanation:
In the above code, we create an array of strings and initialize it with some values. Then, we use the sort() function in C++ to sort the array in descending order using the greater< string>() function object. Finally, we print the sorted array using a loop that iterates over the elements of the array.
Example 4 of sort() Function in C++: Sorting using Custom Comparison Function
We can also define our own custom comparison function as shown in the code given below.
Code:
#include <iostream> #include <algorithm> #include <vector> using namespace std; bool compare(int a, int b) { return a > b; } int main() { vector<int> vec = {5, 2, 7, 3, 1}; sort(vec.begin(), vec.end(), compare); for (int i = 0; i < vec.size(); i++) { cout << vec[i] << " "; } return 0; }
Output:
7 5 3 2 1
Explanation:
In the above example, we defined a custom comparison function compare that takes two integers a and b as arguments and returns true if a is greater than b.
We pass this comparison function as the third parameter to the sort function in C++ to sort the elements in descending order. In the end, we printed the array sorted in descending order on the screen.
Conclusion
In conclusion, the sort function in C++ is a powerful tool for sorting various data structures. It has a simple syntax and can be used with arrays, vectors, and lists. By providing a custom comparison function, we can sort elements in descending order or based on other criteria. All these concepts of sort Function in C++ have been discussed in detail.
Frequently Asked Questions(FAQs)
Here are some Frequently Asked Questions related to sort Function in C++.
Ques 1. Can the sort Function in C++ be used to sort a linked list?
Ans. No, the sort Function in C++ cannot be used to sort a linked list directly
Ques 2. What happens if the container to be sorted is empty?
Ans. If the container to be sorted is empty, the sort function in C++ will do nothing.
Ques 3. Is the sort Function in C++ use a stable sort algorithm?
Ans. Yes, the sort Function in C++ uses a stable sort algorithm.
Ques 4. What happens if you try to sort a container that has elements of different data types?
Ans. If you try to sort a container that has elements of different data types, we will get a compile-time error.
Ques 5. What is the default sorting order of the sort Function in C++?
Ans. The default sorting order of the sort Function in C++ is ascending order.