Learn C++
#include "stlalgorithms/alg_sort.hpp"

Sorting & Searching Algorithms in C++

//concept

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.

//how it works
1

sort everything

std::sort(v.begin(), v.end()); orders ascending with operator< — O(n log n), needs random-access iterators.

2

Custom comparators

Pass a strict-weak-ordering callable ([](auto a, auto b){ return a > b; }) for descending or field-based order.

3

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.

4

Binary search needs sorted

std::binary_search and equal_range assume sorted ranges and answer in O(log n) — sort first, then query freely.

//example
#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;
}
Output
1, 4
1
1sort arranges the range to 1, 2, 3, 4 in O(n log n).
2Endpoints 1 and 4 print — the range is now ordered.
3binary_search probes the sorted range for 3 in O(log n) and reports found (1).
//complexity
time O(n log n) sort, O(log n) binary search
space O(log n)

Introsort recursion depth; binary search is iterative O(1) extra.

//use cases
Ordering anything sortable instead of hand-rolling quicksort
Top-k selection with nth_element when full order is overkill
Membership and range queries on sorted vectors
Descending or field-based orders via one lambda comparator

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.