In the previous post, we described an elegant algorithm that allows to stable sort a container based on fold (also known as std::accumulate or reduce). To make it simpler, we implemented it in Haskell and used it to merge lists.

The subject of today’s post is to:

- Implement this algorithm in C++
- Make it work on the input container directly
- Make it work for more than just lists

In the process, we will build a std::stable_sort variant that works for ForwardIterators, whereas std::stable_sort only works for RandomAccessIterator.

### Implementing the binary counter

Following a quick youtube search, I was able to find an episode of the A9 Stepanov lectures that dealt with the implementation of a binary counter in C++.

The following code is greatly inspired (almost copy-pasted, except for the std::find_if) from these amazing lessons:

- The
*add_to_counter*function handles the carry propagation, and returns the carry if it ran out of bits - The
*reduce_counter*allows to collapse all the remaining bits at the end of the accumulation - The
*binary_counter*class maintains the vector of bits, and is responsible for gluing the algorithms together

As for the Haskell implementation, the C++ implementation of the binary counter is able to deal with any Monoid. It only requires:

- An associative binary operation
- That admits a neutral element

This implementation also shows a great usage of object orientation to structure a program: the class is used to combine some algorithms with the data their operate on (to guaranty invariants), while the algorithms are kept outside of the class for greater re-use.

### The merge binary operation

Now that we have a binary_counter that works on any Monoid, we need to define the equivalent of the SortedList Monoid instance we defined last time in Haskell.

The neutral element will be the empty range, and the binary operation will be something close to *std::merge*. Why something close and not *std::merge* directly? Because we need some kind of auxiliary buffer to perform the merge.

This is the implementation I came to:

I found this implementation more tricky than I first thought it would be. In particular, we need to ensure that the two ranges we merge are always:

- Next to each other (one range end is the beginning of the other)
- In the right order (left range is before the right range)

I claim these two propositions will always hold if we accumulate our container from left to right. The argument is based on the implementation of *add_to_counter* and *reduce_counter* and the properties of Monoids.

Indeed, *reduce_counter* initializes its result from the lower level “bit” (which is the latest arrived in the counter) and combines it on the right with **op(*first, result)**. So the latest arrived range is always provided as right argument of the merge operation.

The same goes for *add_to_counter* that combines the carry on the right side of the binary operation. Again, the latest arrived range is provided as right argument of the merge operation.

This property of the binary_counter algorithm is crucial. The Monoid property guaranties our operation is associative but not necessarily commutative. So the binary_counter must have this property to be correct, and as a result we can rely on it.

### Accumulating with iterators

It is now time to combine our different elements to build our std::stable_sort based on a std::accumulate. But there is a catch…

As observed by Ben Deane in std::accumulate: Exploring an Algorithmic Empire, we cannot really use the std::accumulate of the STL here. It deals with values while we need ranges here, which means iterators.

An easy way to get past this is to create our own accumulate_iter algorithm, that provides an iterator to the accumulating function (instead of a value):

Based on this algorithm, we are now able to assemble the different parts needed to build a std:stable_sort working on *ForwardIterators*:

Now we are truly done. You can convince yourself that it does stable sort a container by trying it on some examples.

### Wrapping it up

We managed to write a std::stable_sort using a variant of std::accumulate that sorts a container provided as parameter. I do not know if this is the same solution Ben Deane used to implement his own, but it is definitively doable.

One interesting consequence is that our stable sort algorithm also works for ForwardIterator. So you can sort a std::list and even a std::forward_list with it.

Now, I would not be offended if you told me you found accumulate_iter usage neither beautiful, nor concise, nor simpler than just implementing a raw loop by hand:

Indeed, C++ may not be the best language to play with fold algorithms. While the Haskell solution was both elegant and concise, you might prefer the imperative style when programming in C++.

Ultimately, deciding which tool and which paradigm to use is a choice you (or your team) have to make.