Skip to content

Instantly share code, notes, and snippets.

@BenGoldberg1
Last active February 28, 2016 01:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BenGoldberg1/b9b510be84dedf13bfe3 to your computer and use it in GitHub Desktop.
Save BenGoldberg1/b9b510be84dedf13bfe3 to your computer and use it in GitHub Desktop.
Fork Sort in C
#include <stdio.h>
int main(int argc, char **argv) {
int count = 1;
char first[1024], current[1024], cmdline[1024];
FILE *lesser = NULL, *greater = NULL;
snprintf( cmdline, sizeof(cmdline), "\"%s\"", argv[0] );
if( NULL == fgets( first, sizeof(first), stdin ) ) return 0;
while( NULL != fgets( current, sizeof(current), stdin ) ) {
int cmp = strcmp( current, first );
if( cmp == 0 ) ++count;
else if( cmp < 0 ) {
if( NULL == lesser ) lesser = popen( cmdline, "w" );
fputs( current, lesser );
} else {
if( NULL == greater ) greater = popen( cmdline, "w" );
fputs( current, greater );
}
}
if( NULL != lesser ) pclose( lesser );
for( ; count; --count ) fputs( first, stdout );
fflush( stdout );
if( NULL != greater ) pclose( greater );
return 0;
}
@BenGoldberg1
Copy link
Author

This code is for demonstration purposes only!

  • The line lengths are limited.
  • It will produce one process per distinct line of data.
  • It will take O(N**2) run time on already sorted data.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment