Taskflow provides template functions for constructing tasks to sort ranges of items in parallel.
You need to include the header file, taskflow/algorithm/sort.hpp, for creating a parallel-sort task.
The task created by tf::Taskflow::sort(B first, E last) sorts the range [first, last) in ascending order using a parallel divide-and-conquer algorithm built on top of introductory sort (introsort). Taskflow recursively splits the range into sub-ranges, sorts each sub-range in parallel across available workers, and merges the sorted sub-ranges back into a fully sorted result. The following diagram illustrates this process on eight elements:
The dashed edges show the recursive splitting phase; the green edges show per-subrange sequential sort at the base case; the orange edges show the parallel merge phase that reconstructs the fully sorted sequence. To correctly use tf::Taskflow::sort, the given iterators must be random-accessible. The following example creates a task that sorts a vector in ascending order:
By default, elements are compared using the operator "<" during the sorting process.
You can pass iterators by reference using std::ref to marshal parameter updates between dependent tasks. This is useful when the range is not known at task-graph construction time but is initialized by an upstream task.
When init finishes, first and last point to the initialized data range of data, and the sort task performs parallel sort over all elements.
tf::Taskflow::sort(B first, E last, C cmp) is an overload of parallel sort that accepts a custom comparator cmp. The following example sorts a vector of integers in descending order:
A custom comparator is especially useful when sorting a range of objects whose natural ordering is not defined by the operator "<". For example, user-defined structs or classes that must be ordered by a specific field. The following example defines a Student struct and sorts a vector of students by GPA in descending order: