aboutsummaryrefslogtreecommitdiff
path: root/sort.c
blob: c2c55fb934b8777f030a258b3a5eb8a5a948860f (plain) (blame)
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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_LINE_LENGTH (2 << 8)
#define LINES_VECTOR_SIZE_INITIAL (2 << 6)
#define LINES_VECTOR_SIZE_INCREMENT (2 << 4)

static int qsort_strcmp(const void *p1, const void *p2);

int main(void)
{
    char **lv;
    unsigned long la, lc, li;

    la = LINES_VECTOR_SIZE_INITIAL;
    lv = (char **) malloc(la * sizeof(char *));

    for (lc = 0 ; ; lc++) {
        if (lc == la) {
            la += LINES_VECTOR_SIZE_INCREMENT;
            lv = (char **) realloc(lv, la * sizeof(char *));
        }
        lv[lc] = (char *) malloc(MAX_LINE_LENGTH * sizeof(char));
        if ((fgets(lv[lc], MAX_LINE_LENGTH, stdin)) == NULL) {
            break;
        }
    }

    qsort(lv, lc, sizeof(char *), qsort_strcmp);

    for (li = 0; li < lc; li++) {
        fputs(lv[li], stdout);
    }

    exit(EXIT_SUCCESS);
}

static int qsort_strcmp(const void *p1, const void *p2)
{
    return strcmp(* (char * const *) p1, * (char * const *) p2);
}