Created
September 4, 2013 04:12
-
-
Save henix/6432677 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <assert.h> | |
#include <stdio.h> | |
#include <string.h> | |
typedef int T; | |
/** | |
* [Sorting network](http://en.wikipedia.org/wiki/Sorting_network) | |
*/ | |
void sort8(T ar[], int n) { | |
static char cmplist2[][2] = {{0, 1}, }; | |
static char cmplist3[][2] = {{0, 1}, {1, 2}, {0, 1} }; | |
static char cmplist4[][2] = {{0, 1}, {2, 3}, {0, 2}, {1, 3}, {1, 2}, }; | |
static char cmplist5[][2] = {{0, 1}, {2, 3}, {0, 2}, {1, 3}, {1, 2}, {3, 4}, {2, 3}, {1, 2}, {0, 1}}; | |
static char cmplist6[][2] = {{0, 1}, {1, 2}, {0, 1}, {3, 4}, {4, 5}, {3, 4}, {0, 3}, {2, 5}, {1, 2}, {3, 4}, {1, 3}, {2, 4}, {2, 3}}; | |
static char cmplist7[][2] = {{0, 1}, {2, 3}, {0, 2}, {1, 3}, {4, 5}, {5, 6}, {4, 5}, {0, 4}, {3, 6}, {1, 2}, {2, 3}, {1, 2}, {4, 5}, {1, 4}, {3, 5}, {2, 3}, {3, 4}, {2, 3}}; | |
static char cmplist8[][2] = {{0, 1}, {2, 3}, {0, 2}, {1, 3}, {1, 2}, {4, 5}, {6, 7}, {4, 6}, {5, 7}, {5, 6}, {0, 4}, {2, 6}, {2, 4}, {1, 5}, {3, 7}, {3, 5}, {1, 2}, {3, 4}, {5, 6}, }; | |
static char lengths[] = {-1, 0, 1, 3, 5, 9, 13, 18, 19}; | |
static char (*lists[])[2] = {NULL, NULL, cmplist2, cmplist3, cmplist4, cmplist5, cmplist6, cmplist7, cmplist8}; | |
assert(n >= 0 && n <= 8); | |
if (n > 1) { | |
char (*list)[2] = lists[n]; | |
int len = lengths[n]; | |
int i; | |
for (i = 0; i < len; ++i) { | |
int a = list[i][0]; | |
int b = list[i][1]; | |
if (ar[a] > ar[b]) { | |
T tmp = ar[a]; | |
ar[a] = ar[b]; | |
ar[b] = tmp; | |
} | |
} | |
} | |
} | |
int main(int argc, char const *argv[]) | |
{ | |
int ar[] = {2, 4, 3, 5, 6, 1, 7}; | |
sort8(ar, 7); | |
int i; | |
for (i = 0; i < 7; ++i) { | |
printf("%d ", ar[i]); | |
} | |
putchar('\n'); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment