ArticleslgStudy

computer science

Sort (C++)

Sort (C++) is a computer science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand Sort (C++) rather than just read about it. In short: sort is a generic function in the C++ Standard Library for doing comparison sorting. The function originated in the Standard Template Library (STL).

Key takeaways

  • Sort (C++) belongs to computer science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect Sort (C++) to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of Sort (C++) from memory before moving on to harder problems.

Reference excerpt

sort is a generic function in the C++ Standard Library for doing comparison sorting. The function originated in the Standard Template Library (STL). The specific sorting algorithm is not mandated by the language standard and may vary across implementations, but the worst-case asymptotic complexity of the function is specified: a call to sort must perform no more than O(N log N) comparisons when applied to a range of N elements.

Usage The sort function is included from the <algorithm> header of the C++ Standard Library, and carries three arguments: RandomAccessIterator first, RandomAccessIterator last, Compare comp. Here, RandomAccessIterator is a templated type that must be a random access iterator, and first and last must define a sequence of values, i.e., last must be reachable from first by repeated application of the increment operator to first. The third argument, also of a templated type, denotes a comparison predicate. This comparison predicate must define a strict weak ordering on the elements of the sequence to be sorted. The third argument is optional; if not given, the "less-than" (<) operator is used (or the function object std::less), which may be overloaded in C++. This code sample sorts a given array of integers (in ascending order) and prints it out.

The same functionality using a std::vector container, using its begin and end methods to obtain iterators:

Beginning with C++20 and the std::ranges library, sorting can be done over a range.

Genericity sort is specified generically, so that it can work on any random-access container and any way of determining that an element x of such a container should be placed before another element y. Although generically specified, sort is not easily applied to all sorting problems. A particular problem that has been the subject of some study is the following:

Let A and B be two arrays, where there exists some relation between the element A[i] and the element B[i] for all valid indices i. Sort A while maintaining the relation with B, i.e., apply the same permutation to B that sorts A. Do the previous without copying the elements of A and B into a new array of pairs, sorting, and moving the elements back into the original arrays (which would require O(n) temporary space). A solution to this problem was suggested by A. Williams in 2002, who implemented a custom iterator type for pairs of arrays and analyzed some of the difficulties in correctly implementing such an iterator type. Williams's solution was studied and refined by K. Åhlander.

Complexity and implementations The C++ standard requires that a call to sort performs O(N log N) comparisons when applied to a range of N elements. In previous versions of C++, such as C++03, only average complexity was required to be O(N log N). This was to allow the use of algorithms like (median-of-3) quicksort, which are fast in the average case, indeed significantly faster than other algorithms like heap sort with optimal worst-case complexity, and where the worst-case quadratic complexity rarely occurs. The introduction of hybrid algorithms such as introsort allowed both fast average performance and optimal worst-case performance, and thus the complexity requirements were tightened in later standards. Different implementations use different algorithms. The GNU Standard C++ library, for example, uses a 3-part hybrid sorting algorithm: introsort is performed first (introsort itself being a hybrid of quicksort and heap sort), to a maximum depth given by 2×log2 n, where n is the number of elements, followed by an insertion sort on the result.

Other types of sorting sort is not stable: equivalent elements that are ordered one way before sorting may be ordered differently after sorting. stable_sort ensures stability of result at expense of worse performance (in some cases), requiring only quasilinear time with exponent 2 – O(n log2 n) – if additional memory is not available, but linearithmic time O(n log n) if additional memory is available. This allows the use of in-place merge sort for in-place stable sorting and regular merge sort for stable sorting with additional memory. Partial sorting is implemented by partial_sort, which takes a range of n elements and an integer m < n, and reorders the range so that the smallest m elements are in the first m positions in sorted order (leaving the remaining n − m in the remaining positions, in some unspecified order). Depending on design this may be considerably faster than complete sort. Historically, this was commonly implemented using a heap-based algorithm that takes Θ(n + m log n) worst-case time. A better algorithm called quickselsort is used in the Copenhagen STL implementation, bringing the complexity down to Θ(n + m log m). Selection of the nth element is implemented by nth_element, which actually implements an in-place partial sort: it correctly sorts the nth element, and also ensures that this element partitions so elements before it are less than it, and elements after it are greater than it. There is the requirement that this takes linear time on average, but there is no worst-case requirement; these requirements are exactly met by quickselect, for any choice of pivot strategy. Some containers, among them std::list (a linked list), provide a specialised version of sort as a member function. This is because linked lists don't have random access (and therefore can't use the regular sort function); and the specialised version also preserves the values list iterators point to.

Comparison to qsort Aside from sort, the C++ standard library also includes the qsort function from the C standard library (from <cstdlib>). Compared to qsort, the templated sort is more type-safe since it does not require access to data items through unsafe void pointers, as qsort does. Also, qsort accesses the comparison function using a function pointer, necessitating large numbers of repeated function calls, whereas in sort, comparison functions may be inlined into the custom object code generated for a template instantiation. In practice, C++ code using sort is often considerably faster at sorting simple data like integers than equivalent C code using qsort.

References

External links C++ reference for std::sort Another C++ reference for std::sort

Worked examples

Example 1 — a first encounter with Sort (C++)

Start with the simplest possible case. Write down what Sort (C++) claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In computer science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to Sort (C++) before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about Sort (C++) ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of Sort (C++)

In research
Sort (C++) appears in computer science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses Sort (C++) in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
Sort (C++) is common in secondary-school and first-year university syllabi. It links to neighbouring topics C++ Standard Library, Sorting algorithms, so understanding it makes those chapters shorter.
In everyday life
Look for Sort (C++) outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.
Ask Teacher Smith questions about this articleOpens your AI tutor with a question about “Sort (C++)” →

Affiliate

Preply — study more efficiently by working with a personal tutor. 50% off.

How to study Sort (C++) in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what Sort (C++) means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain Sort (C++) out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is Sort (C++) in simple terms?

sort is a generic function in the C++ Standard Library for doing comparison sorting. The function originated in the Standard Template Library (STL).

Why does Sort (C++) matter?

Because it connects several computer science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study Sort (C++)?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on Sort (C++).

Tags

  • C++ Standard Library
  • Sorting algorithms

Keep exploring