Sorting in C++
sorting in C++
Sorting in C++ can be done in various ways depending on the sorting algorithm you want to
use. C++ provides a standard library function std::sort that makes it easy to sort
containers like arrays, vectors, etc.
1. Using std::sort
std::sort is part of the <algorithm> library and allows you to sort in ascending order by
default.
Example:
cpp
#include <iostream>
#include <algorithm>
#include <vector>
int main() {
std::vector<int> vec = {3, 1, 4, 1, 5, 9, 2, 6};
std::sort(vec.begin(), vec.end());
std::cout << "Sorted vector: ";
for (int num : vec) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
Output:
arduino
Sorted vector: 1 1 2 3 4 5 6 9
2. Descending Order Sorting
1/4
To sort in descending order, you can provide a custom comparison function or use a lambda
expression.
Example (Descending Order):
cpp
#include <iostream>
#include <algorithm>
#include <vector>
int main() {
std::vector<int> vec = {3, 1, 4, 1, 5, 9, 2, 6};
std::sort(vec.begin(), vec.end(), std::greater<int>());
std::cout << "Sorted in descending order: ";
for (int num : vec) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
Output:
csharp
Sorted in descending order: 9 6 5 4 3 2 1 1
3. Custom Sorting (Using a Lambda Function)
You can also provide a custom comparison function, for example, to sort in a way other than
just ascending or descending.
Example (Custom Sorting):
cpp
#include <iostream>
#include <algorithm>
#include <vector>
2/4
int main() {
std::vector<int> vec = {3, 1, 4, 1, 5, 9, 2, 6};
// Custom sort: sort by even numbers first, then odd numbers
std::sort(vec.begin(), vec.end(), [](int a, int b) {
if (a % 2 == 0 && b % 2 != 0) return true;
if (a % 2 != 0 && b % 2 == 0) return false;
return a < b; // If both are even or both are odd, sort normally
});
std::cout << "Custom sorted vector: ";
for (int num : vec) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
Output:
arduino
Custom sorted vector: 2 4 6 1 1 3 5 9
4. Sorting Arrays
You can also sort regular arrays with std::sort .
Example (Array Sorting):
cpp
#include <iostream>
#include <algorithm>
int main() {
int arr[] = {3, 1, 4, 1, 5, 9, 2, 6};
int n = sizeof(arr) / sizeof(arr[0]);
std::sort(arr, arr + n);
3/4
std::cout << "Sorted array: ";
for (int i = 0; i < n; ++i) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
return 0;
}
Output:
Sorted array: 1 1 2 3 4 5 6 9
5. Time Complexity
Average/Best Case Time Complexity: O(n log n)
Worst Case Time Complexity: O(n log n) for std::sort (but O(n²) for some other
algorithms like bubble sort).
Would you like to see how to implement a specific sorting algorithm (e.g., bubble sort,
quicksort, merge sort)?
4/4