1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

void swap(char *args1, char *args2) {
	char tmp[40];
	strcpy( tmp, args1 );
	strcpy( args1, args2 );
	strcpy( args2, tmp );
}

void sort(char ** args, const int start, const int end) {
	char *pivot = args[end];
	int i = start-1, j = start;
	while( j < end ) {
		int cmp = strcmp( pivot, args[j] );
		if( cmp > 0 )
			swap( args[++i], args[j] );
		j++;
	}
	swap( args[++i], pivot );
	if( start + 1 < i )
		sort( args, start, i - 1 );
	if( end - 1 > i )
		sort( args, i + 1, end );
}

void wsort(char ** args, const int count) {
	sort( args, 0, count - 1 );
}

int main() {
	const int length = 40;
	const int increment = 20;
	int size = 20;
	printf( "Insert words consisting of up to %d characters. One word for each line.\n", length );
	char **buffer = calloc( size, sizeof(char *) );
	if( !buffer )
		return 1;
	int i = 0;
	for(;;) {
		buffer[i] = calloc( length, sizeof(char) );
		if( !buffer[i] )
			return 2;
		if( !fgets( buffer[i], length, stdin ) )
			break;
		i++;
		if( i == size ) {
			buffer = realloc( buffer, (size+=increment) * length * sizeof(char *) );
			if( !buffer )
				return 3;
		}
	}
	printf( "%d items will be sorted now...\n", i );
	wsort( buffer, i );
	printf( "Sorting complete. Here is the resulting list:\n" );
	for( int j = 0; j < i; j++ )
		printf( "%s", buffer[j]  );
}