Array Sorting Techniques with C++ Standard Algorithm
Function Signature and Requirements
The sorting utility is provided by the <algorithm> header. The function accepts a starting iterator, an ending iterator, and an optional comparison predicate. Without a custom predicate, elements are ordered in ascending sequence. This utility is generic and supports any data type that implements comparison operators, including characters and strings.
Ascending Order Configuration
Omitting the third argument triggers the default ascending sort.
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
int count;
std::cin >> count;
std::vector<int> data(count);
for (int idx = 0; idx < count; ++idx) {
std::cin >> data[idx];
}
std::sort(data.begin(), data.end());
for (int val : data) {
std::cout << val << " ";
}
std::cout << "\n";
return 0;
}
Descending Order Configuration
To reverse the sequence, supply a binary predicate that returns true when the first argument should precede the second.
#include <iostream>
#include <vector>
#include <algorithm>
bool descendingOrder(int lhs, int rhs) {
return lhs > rhs;
}
int main() {
int count;
std::cin >> count;
std::vector<int> data(count);
for (int idx = 0; idx < count; ++idx) {
std::cin >> data[idx];
}
std::sort(data.begin(), data.end(), descendingOrder);
for (int val : data) {
std::cout << val << " ";
}
std::cout << "\n";
return 0;
}
Character and String Sequences
Lexicographical and ASCII value comparisons are applied automatically for textual data types.
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
bool reverseString(const std::string& lhs, const std::string& rhs) {
return lhs > rhs;
}
int main() {
int count;
std::cin >> count;
std::vector<char> chars(count);
std::vector<std::string> words(count);
for (int idx = 0; idx < count; ++idx) std::cin >> chars[idx];
for (int idx = 0; idx < count; ++idx) std::cin >> words[idx];
std::sort(chars.begin(), chars.end());
std::sort(words.begin(), words.end(), reverseString);
for (char c : chars) std::cout << c << " ";
std::cout << "\n";
for (const auto& w : words) std::cout << w << " ";
std::cout << "\n";
return 0;
}