aboutsummaryrefslogtreecommitdiff
path: root/t/helper/test-mergesort.c
blob: ea3b959e94ff6f53726d4fce955bca1181a3be07 (plain)
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
#include "cache.h"
#include "mergesort.h"

struct line {
	char *text;
	struct line *next;
};

static void *get_next(const void *a)
{
	return ((const struct line *)a)->next;
}

static void set_next(void *a, void *b)
{
	((struct line *)a)->next = b;
}

static int compare_strings(const void *a, const void *b)
{
	const struct line *x = a, *y = b;
	return strcmp(x->text, y->text);
}

int main(int argc, char **argv)
{
	struct line *line, *p = NULL, *lines = NULL;
	struct strbuf sb = STRBUF_INIT;

	for (;;) {
		if (strbuf_getwholeline(&sb, stdin, '\n'))
			break;
		line = xmalloc(sizeof(struct line));
		line->text = strbuf_detach(&sb, NULL);
		if (p) {
			line->next = p->next;
			p->next = line;
		} else {
			line->next = NULL;
			lines = line;
		}
		p = line;
	}

	lines = llist_mergesort(lines, get_next, set_next, compare_strings);

	while (lines) {
		printf("%s", lines->text);
		lines = lines->next;
	}
	return 0;
}