summaryrefslogtreecommitdiff
path: root/test-mergesort.c
diff options
context:
space:
mode:
authorRené Scharfe <rene.scharfe@lsrfire.ath.cx>2012-03-31 22:10:11 (GMT)
committerJunio C Hamano <gitster@pobox.com>2012-04-11 15:50:53 (GMT)
commit0db71e0fa94c1857f98890928098e8f4c8ac6f26 (patch)
tree0095038b4c0b0c9d643380f479cb17db1dcd14a6 /test-mergesort.c
parent828ea97de486c1693d6e4f2c7347acb50235a85d (diff)
downloadgit-0db71e0fa94c1857f98890928098e8f4c8ac6f26.zip
git-0db71e0fa94c1857f98890928098e8f4c8ac6f26.tar.gz
git-0db71e0fa94c1857f98890928098e8f4c8ac6f26.tar.bz2
add mergesort() for linked lists
This adds a generic bottom-up mergesort implementation for singly linked lists. It was inspired by Simon Tatham's webpage on the topic[1], but not so much by his implementation -- for no good reason, really, just a case of NIH. [1] http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html Signed-off-by: Rene Scharfe <rene.scharfe@lsrfire.ath.cx> Signed-off-by: Junio C Hamano <gitster@pobox.com>
Diffstat (limited to 'test-mergesort.c')
-rw-r--r--test-mergesort.c52
1 files changed, 52 insertions, 0 deletions
diff --git a/test-mergesort.c b/test-mergesort.c
new file mode 100644
index 0000000..1dd82fd
--- /dev/null
+++ b/test-mergesort.c
@@ -0,0 +1,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, const 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 = mergesort(lines, get_next, set_next, compare_strings);
+
+ while (lines) {
+ printf("%s", lines->text);
+ lines = lines->next;
+ }
+ return 0;
+}