Accumulating your merge sort

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:

  1. Next to each other (one range end is the beginning of the other)
  2. 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.

Folding your merge sort

Back in September 2016, I was lucky enough to attend a talk from Ben Deane entitled std::accumulate: Exploring an Algorithmic Empire. In this talk, he presents the unknown possibilities of std::accumulate, an algorithm also known as fold or reduce depending on the language.

The arguments were already quite compelling… then came the slide in which he announced he had implemented almost all the algorithms of the STL based on std::accumulate (41st minute in the video).

From the Haskell world, I already knew most one-pass algorithm could be implemented in terms of a fold. But there are algorithms in the list that are not simple linear scan, like std::stable_sort. How is it possible?

I searched his blog and could not find a hit on how he did it. So I write this post to describe the solution I found. I hope you will find it as elegant as I do.

 

Small ranges and binary counters


The solution relies on using a binary counter like data-structure. Our binary counter will hold at each level L a range of size 2^L. The binary counter will thus be limited in size to log(N) if N is the number of elements of the collection to sort.

We populate the binary counter by successively adding ranges of size one to the counter. Each time we have a collision of “bit” (range of the same size), we merge them and consider it as a “carry”. We keep propagating the carry up the levels, until we reach an empty slot.

This is best explained by an example:

Initially
Counter = [[1, 2], [3, 4, 5, 6]]

Adding element 7
Counter = [[7], [1, 2], [3, 4, 5, 6]]

Adding element 8
Counter = [merge [8] and [7], [1, 2], [3, 4, 5, 6]]
Counter = [merge [7, 8] and [1, 2], [3, 4, 5, 6]]
Counter = [merge [1, 2, 7, 8] and [3, 4, 5, 6]]
Counter = [[1, 2, 3, 4, 5, 6, 7, 8]]

Adding elements 9, 10 and 11
Counter = [[11], [9, 10], [1, 2, 3, 4, 5, 6, 7, 8]]

 
At this point, we are almost done, but not quite. We still need to collapse all the remaining “bits” of our counter into one answer. We do this by accumulating over these “bits” with a merge operation.

[[11], [9, 10], [1, 2, 3, 4, 5, 6, 7, 8]]
[[9, 10, 11], [1, 2, 3, 4, 5, 6, 7, 8]]
[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]]

 
We are done! Let us try to implement this in Haskell.

 

Haskell implementation


The implementation in Haskell follows pretty closely the description we gave of the solution in the previous paragraph.

The main difference lies in the use of an auxiliary integer to keep the length of the list. Had we not do that, our solution would have been much less efficient: computing the length of a list in Haskell is linear in the size of the list.

  • The head of the counter list is the lowest level bit
  • The function propagate implements the carry propagation
  • The function addToCounter add a “bit” in the counter
  • The map snd allows to get rid of the integer holding the list length
  • The foldl1 (flip merge) implements the collapse of the counter

To ensure our merge sort is stable, ranges that came last must be passed as right parameters to the merge function. This is the reason why we collapse our counter with flip merge instead of merge that would also type check.

This implementation assumes the existence of a merge function that combines two sorted lists into one bigger sorted list. You can implement it as follows (it requires a bit of care to make it stable):

 
As map (std::transform in the STL) can be itself implemented in terms of fold (std::accumulate), this is one way to implement a “out of place” stable sort in Haskell based only on folds and composition of functions.

 

Generalizing to Monoids


Looking back at the code of our solution, we can observe that this algorithm would work for any Monoid. So we can make our algorithm more general, and fold any Monoid following a tree like structure.

 
To get our stable merge sort back, we can create a type for sorted lists, and make it an instance of Monoid. Here is one possible implementation:

 

Conclusion and what’s next


I was quite astonished how elegant the solution was and how simple the resulting code. But somehow, you should feel unsatisfied with the performance.

I cheated. I did not use C++ as the original presentation did. And this implementation of stable_sort creates a new list. Haskell did not give me the choice.

So next time we will have a look at an implementation in C++ that stable sorts the container provided as input.