bhylu.com

Advertisements

C++ Sorting and Binary Search

Use ranges algorithms and state the ordering precondition that makes binary search valid.

How it works

Sorting arranges a range according to a comparison relation. Binary search relies on a compatible partition/order precondition; it is not a faster substitute for scanning arbitrary unsorted data. A C++20 ranges call can accept a container directly, reducing mismatched begin/end pairs. Keep the same comparison policy between sorting and searching. If values are frequently inserted, include the cost of maintaining that order when choosing the representation.

Run it locally

Use a C++20 compiler and matching standard library in a separate lab folder. The command uses c++; substitute g++, clang++ or zig c++ for your toolchain. C++ does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed.

c++ -std=c++20 -Wall -Wextra -Wpedantic -Werror sorting-search.cpp -o lesson

On Windows use -o lesson.exe and run .\lesson.exe in PowerShell. On Unix-like systems run ./lesson. Thread examples may need -pthread on your platform.

Download the complete C++ source. Run file labs in a private empty directory, away from existing reports.

Example

C++20 · sorting-search.cpp

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> loads{7, 2, 5, 2};
    std::ranges::sort(loads);
    std::cout << "Has 5: " << std::ranges::binary_search(loads, 5) << '\n';
    for (int value : loads) { std::cout << value << ' ' ; }
    std::cout << '\n';
}

Expected result

Has 5: 1
2 2 5 7 

The two equal values remain present; sorting does not remove duplicates. The default numeric ordering is consistent for this integer fixture. A custom comparator should compare values without overflow, for example using relational operators rather than subtracting arbitrary ints. Stable sorting is a separate requirement if equal keys must retain their original order.

Consult the WG21 C++ working group and the C++ Core Guidelines for language references and design guidance. Check the selected standard version and your implementation’s library support.