Standard sorting networks for small values of n

前端 未结 3 1306
感动是毒
感动是毒 2020-12-29 10:26

I\'m looking for a sorting network implementation of a 5-element sort, but since I couldn\'t find a good reference on SO, I\'d like to ask for sorting networks for all small

3条回答
  •  不思量自难忘°
    2020-12-29 10:40

    Too long for a comment. Prof Falken's answer above can be validated in MATLAB along the following lines: using a bit of find/replacing or regex-fu, write

    sn{3} = [...
        [[1,2],[1,3],[2,3]];...
        [[1,2],[2,3],[1,2]];...
        [[1,3],[1,2],[2,3]];...
        [[1,3],[2,3],[1,2]];...
        [[2,3],[1,2],[2,3]];...
        [[2,3],[1,3],[1,2]];
        ];
    

    and similarly for the other values of n, then run

    for n = 3:6
        test_in = cellfun(@str2num,num2cell(dec2bin(0:(2^n-1),n)));
        for j = 1:size(sn{n},1)
            test_out = test_in;
            for k = 1:2:size(sn{n},2)
                temp1 = test_out(:,sn{n}(j,k));
                temp2 = test_out(:,sn{n}(j,k+1));
                ind = temp2 < temp1;
                test_out(ind,sn{n}(j,k)) = temp2(ind);
                test_out(ind,sn{n}(j,k+1)) = temp1(ind);
            end
        end
        test = cellfun(@issorted,mat2cell(test_out,ones(1,2^n),n));
        assert(all(test),['n = ',num2str(n),' failed test']);   
    end
    

    The assertions hold for each value of n.

提交回复
热议问题