fork download
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<string.h>
  4.  
  5. void swap(char **args1, char **args2) {
  6. char *tmp = *args1;
  7. *args1 = *args2;
  8. *args2 = tmp;
  9. }
  10. void sort(char ** args, const int start, const int end) {
  11. char *pivot = args[end];
  12. int i = start-1, j = start;
  13. while( j < end ) {
  14. int cmp = strcmp( pivot, args[j] );
  15. if( cmp > 0 )
  16. swap( &args[++i], &args[j] );
  17. j++;
  18. }
  19. swap( &args[++i], args+end );
  20. if( start + 1 < i )
  21. sort( args, start, i - 1 );
  22. if( end - 1 > i )
  23. sort( args, i + 1, end );
  24. }
  25.  
  26. void wsort(char ** args, const int count) {
  27. sort( args, 0, count - 1 );
  28. }
  29.  
  30. int main() {
  31. const int length = 40;
  32. const int increment = 20;
  33. int size = 20;
  34. printf( "Insert words consisting of up to %d characters. One word for each line.\n", length );
  35. char **buffer = calloc( size, sizeof(char *) );
  36. if( !buffer )
  37. return 1;
  38. int i = 0;
  39. for(;;) {
  40. buffer[i] = calloc( length, sizeof(char) );
  41. if( !buffer[i] )
  42. return 2;
  43. if( !fgets( buffer[i], length, stdin ) )
  44. break;
  45. i++;
  46. if( i == size ) {
  47. buffer = realloc( buffer, (size+=increment) * length * sizeof(char *) );
  48. if( !buffer )
  49. return 3;
  50. }
  51. }
  52. printf( "%d items will be sorted now...\n", i );
  53. wsort( buffer, i );
  54. printf( "Sorting complete. Here is the resulting list:\n" );
  55. for( int j = 0; j < i; j++ )
  56. printf( "%s", buffer[j] );
  57. }
Success #stdin #stdout 0.02s 1856KB
stdin
Bravo
Charlie
Delta
Alpha
Alf

stdout
Insert words consisting of up to 40 characters. One word for each line.
6 items will be sorted now...
Sorting complete. Here is the resulting list:

Alf
Alpha
Bravo
Charlie
Delta