Stability in column layout

I was reading the notes on programming PDF and found a discussion about writing min and max functions for multiple arguments. I didn't what to use this for. Also there was a discussion about stability. Stability is when you leave elements in the same position when they're the same. This seems to be about sorting.

At the same I was implementing a Pinterest like column layout. I already had a working version. But sometimes the images weren't loaded completely and the algorithm would overlap images, because the height of the element wasn't known.

So I started searching for solutions to this problem and found this answer on StackOverflow from the creator of the Pinterest layout himself. He doesn't have the solution to my problem, but suggests to put the element in the shortest column. This will solve a problem that I hadn't seen yet.

So I implemented the following:

function min(cols) {
    return (cols[0] < cols[1]) ? 0 : 1;

$(window).load(function() {
    var start = 100;
    var cols = [ start, start ];
    var w    = [ 0, 330 ];

    $('.submission').each(function() {
        var col = min(cols);

        var height = $(this).height();
        $(this).css('left', w[col]+ 'px');
        $(this).css('top', cols[col]+ 'px');
        $(this).css('width', '320px');
        cols[col] += height + 32;

As you can see in this case with two columns we can pick a column based on the height of column. At first I didn't think this had anything to do with stability. But it does. If you run this code the first element will be inserted in the right column. This is because the 0 in column 0 is not smaller than the 0 in column 1, it's equal. The min function will return 1 in this case, which is the right column.

Stability in the case of column selection is that the algorithm prefers to insert the element in the left column instead of the right column in case of equal heights.

There is a simple change that should be made to the min function to fix this problem. We need to swap the operands of the < operator and the return values so we don't lose stability.

function min(cols) {
    return (cols[1] < cols[0]) ? 1 : 0;

Properties like stability are general and also apply to Javascript.


My name is Peter Stuifzand. You're reading my personal website.