How to fix this non-recursive odd-even-merge sort algorithm?

前端 未结 3 1435
南旧
南旧 2021-01-04 11:00

I was searching for non-recursive odd-even-merge sort algorithm and found 2 sources:

  • a book from Sedgewick R.
  • this SO question

Both alg

3条回答
  •  滥情空心
    2021-01-04 11:07

    I think I found a solution. I checked it for length = 2, 4, 8, 16.

    Here is my code:

    void sort(int length)
    { int G = log2ceil(length);                      // number of groups
      for (int g = 0; g < G; g++)                    // iterate groups
      { int B = 1 << (G - g - 1);                    // number of blocks
        for (int b = 0; b < B; b++)                  // iterate blocks in a group
        { for (int s = 0; s <= g; s++)               // iterate stages in a block
          { int d = 1 << (g - s);                    // compare distance
            int J = (s == 0) ? 0 : d;                // starting point
            for (int j = J; j+d < (2<

    This solution introduces a fifth for-loop to handle subblocks in a group. The j loop has a changed start and abort value to handle odd counts of post merge steps without generating doubled compare steps.

提交回复
热议问题