Permalink
Browse files

Just use qsort, heapsort, and mergesort from stdlib.

  • Loading branch information...
1 parent 7e56885 commit ec3b242fd0920f0be2ee6d9b654a371b037a8155 @zedshaw committed Apr 11, 2012
Showing with 120 additions and 0 deletions.
  1. +22 −0 src/lcthw/darray_algos.c
  2. +16 −0 src/lcthw/darray_algos.h
  3. +82 −0 tests/darray_algos_tests.c
@@ -0,0 +1,22 @@
+#include <lcthw/darray_algos.h>
+#include <stdlib.h>
+
+
+int DArray_qsort(DArray *array, DArray_compare cmp)
+{
+ qsort(array->contents, DArray_count(array), sizeof(void *), cmp);
+ return 0;
+}
+
+
+int DArray_heapsort(DArray *array, DArray_compare cmp)
+{
+ return heapsort(array->contents, DArray_count(array), sizeof(void *), cmp);
+}
+
+
+int DArray_mergesort(DArray *array, DArray_compare cmp)
+{
+ return mergesort(array->contents, DArray_count(array), sizeof(void *), cmp);
+}
+
@@ -0,0 +1,16 @@
+#ifndef darray_algos_h
+#define darray_algos_h
+
+#include <lcthw/darray.h>
+#include <lcthw/dbg.h>
+
+
+typedef int (*DArray_compare)(const void *a, const void *b);
+
+int DArray_qsort(DArray *array, DArray_compare cmp);
+
+int DArray_heapsort(DArray *array, DArray_compare cmp);
+
+int DArray_mergesort(DArray *array, DArray_compare cmp);
+
+#endif
@@ -0,0 +1,82 @@
+#include "minunit.h"
+#include <lcthw/darray_algos.h>
+
+int testcmp(char **a, char **b)
+{
+ return strcmp(*a, *b);
+}
+
+DArray *create_words()
+{
+ DArray *result = DArray_create(0, 5);
+ char *words[] = {"asdfasfd", "werwar", "13234", "asdfasfd", "oioj"};
+ int i = 0;
+
+ for(i = 0; i < 5; i++) {
+ DArray_push(result, words[i]);
+ }
+
+ return result;
+}
+
+int is_sorted(DArray *array)
+{
+ int i = 0;
+
+ for(i = 0; i < DArray_count(array) - 1; i++) {
+ if(strcmp(DArray_get(array, i), DArray_get(array, i+1)) > 0) {
+ return 0;
+ }
+ }
+
+ return 1;
+}
+
+char *test_qsort()
+{
+ DArray *words = create_words();
+ mu_assert(!is_sorted(words), "Words should start not sorted.");
+
+ DArray_qsort(words, (DArray_compare)testcmp);
+ mu_assert(is_sorted(words), "qsort failed");
+
+ DArray_destroy(words);
+ return NULL;
+}
+
+char *test_heapsort()
+{
+ DArray *words = create_words();
+
+ DArray_heapsort(words, (DArray_compare)testcmp);
+ mu_assert(is_sorted(words), "heapsort failed");
+
+ DArray_destroy(words);
+ return NULL;
+}
+
+char *test_mergesort()
+{
+ DArray *words = create_words();
+
+ DArray_mergesort(words, (DArray_compare)testcmp);
+ mu_assert(is_sorted(words), "mergesort failed");
+
+ DArray_destroy(words);
+ return NULL;
+}
+
+
+char * all_tests()
+{
+ mu_suite_start();
+
+ mu_run_test(test_qsort);
+ mu_run_test(test_heapsort);
+ mu_run_test(test_mergesort);
+
+ return NULL;
+}
+
+RUN_TESTS(all_tests);
+

0 comments on commit ec3b242

Please sign in to comment.