Sorting & Searching Algorithms in C++
std::sort (from <algorithm>) orders any random-access range in O(n log n) — typically introsort, a quicksort/heapsort hybrid that dodges worst cases. Partial needs are cheaper: nth_element partitions around the k-th item in O(n) without fully sorting, and binary_search plus equal_range query sorted ranges in O(log n).
Custom order arrives via comparator (lambda or operator<): sort(v.begin(), v.end(), greater<int>()) sorts descending. Sorting is the gateway drug of algorithms — half the library assumes sorted input.
sort everything
std::sort(v.begin(), v.end()); orders ascending with operator< — O(n log n), needs random-access iterators.
Custom comparators
Pass a strict-weak-ordering callable ([](auto a, auto b){ return a > b; }) for descending or field-based order.
nth_element for top-k
std::nth_element(first, kth, last) places the k-th element correctly in O(n) — everything before compares smaller, unsorted.
Binary search needs sorted
std::binary_search and equal_range assume sorted ranges and answer in O(log n) — sort first, then query freely.
#include <iostream>#include <vector>#include <algorithm> int main() { std::vector<int> v{4, 1, 3, 2}; std::sort(v.begin(), v.end()); std::cout << v[0] << ", " << v[3] << std::endl; std::cout << std::binary_search(v.begin(), v.end(), 3) << std::endl; return 0;}Introsort recursion depth; binary search is iterative O(1) extra.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself — building beats watching.