Network sorting - which networks allow you to skip comparisons?

The GCC implementation qsortuses median 3 to select a support rod. While he has 3 items sorted with a sorting network.

A sorting network for 3 items usually requires 3 comparisons. But in this particular implementation, the last comparison may be skipped, depending on the comparison, to:

if(a[0] > a[1]) swap(a[0], a[1]);
if(a[1] > a[2]) swap(a[1], a[2]);
else goto jump;
if(a[0] > a[1]) swap(a[0], a[1]);
jump:;

Is it possible to do something similar for networks with n = 4...16(those that have a known minimum optimal number of comparisons)? If so, what and how do they look?

UPDATE: So far, I have found another network that allows you to skip one comparison:

// sorting network for 5 elements
if (a[0] > a[1]) { SWAP(a[0], a[1]); }
if (a[2] > a[3]) { SWAP(a[2], a[3]); }

if (a[1] > a[3]) { SWAP(a[1], a[3]); }
if (a[2] > a[4]) { SWAP(a[2], a[4]); }

if (a[0] > a[2]) { SWAP(a[0], a[2]); }
if (a[1] > a[4]) { SWAP(a[1], a[4]); }

if (a[1] > a[2]) { SWAP(a[1], a[2]); }
if (a[3] > a[4]) { SWAP(a[3], a[4]); }
else { goto jump; }

if (a[2] > a[3]) { SWAP(a[2], a[3]); }
jump:;

I tested this with all 12345 permutations and it sorts them all correctly.

+4
1

, n + 1 n, n , ( ):

insert sorting network n + 1

, n + 1 , , n n + 1. , n false, . , .

, , , : .

- , , / , 4 , , , , .

0

Source: https://habr.com/ru/post/1656987/


All Articles