![]() |
VOOZH | about |
Sorting is one of the most basic operations applied to data. It means arranging the data in a particular order, which can be increasing, decreasing or any other order. In this article, we will discuss various ways of sorting in C++.
C++ provides a built-in function in C++ STL called sort() as the part of <algorithm> library for sorting the containers such as arrays, vectors, deque, etc.
sort(first, last, comp);
where,
Let's take a look at an example that sorts the given vector in ascending order:
1 2 3 4 5
The sort() function implements the introsort sorting algorithm which is a combination of insertion sort, quick sort and heap sort. It automatically determines which algorithm to use according to the dataset.
Sorting data is a common operation in programming.
Unfortunately, C++ does not provide implementation of any other sorting algorithm than Introsort and we can also not instruct to execute a particular algorithm to sort method. So, if we need a different sorting algorithm such as counting sort, we have to implement it by ourselves.
Bubble Sort is a comparison-based sorting algorithm. It works by repeatedly swapping adjacent elements if they are in the wrong order, placing one element to its correct position in each iteration. Let's take a look at its implementation:
1 2 3 4 5
Counting Sort is a non-comparison-based sorting algorithm. It works by counting the frequency of each distinct element in the input and use that information to place the elements in their correct sorted positions. Let's take a look at its implementation:
1 2 3 4 5
In a similar way, we can implement any sorting algorithm of our choice and need.
As told earlier, sorting is one of the frequently used operations on data. It is used in solving a lot of programming problems. The below examples demonstrate the use of sort() in different problems:
1 2 3 4 5
3
1, 2