Skip to content

Commit 7b54a58

Browse files
committed
Fix zlistx_sort edge case
1 parent 6b435f5 commit 7b54a58

1 file changed

Lines changed: 41 additions & 0 deletions

File tree

src/zlistx.c

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -479,6 +479,8 @@ zlistx_sort (zlistx_t *self)
479479
bool swapped = false;
480480
while (gap > 1 || swapped) {
481481
gap = (size_t) ((double) gap / 1.3);
482+
if (gap < 1)
483+
gap = 1;
482484
node_t *base = self->head->next;
483485
node_t *test = self->head->next;
484486
size_t jump = gap;
@@ -741,6 +743,43 @@ zlistx_unpack (zframe_t *frame) {
741743
// --------------------------------------------------------------------------
742744
// Runs selftest of class
743745

746+
static int compare_ints(const void *item1, const void *item2) {
747+
int val1 = *(int*)item1;
748+
int val2 = *(int*)item2;
749+
if (val1 > val2) return 1;
750+
if (val1 < val2) return -1;
751+
return 0;
752+
}
753+
754+
static void test_numeric_sort() {
755+
// Test numeric sort
756+
zlistx_t *list = zlistx_new();
757+
zlistx_set_comparator(list, compare_ints);
758+
759+
int values[] = {5,10,8,7,6,4,2,9,1,11};
760+
size_t nitems = sizeof(values) / sizeof(int);
761+
762+
for (int i = 0; i < nitems; i++) {
763+
zlistx_add_end(list, &values[i]);
764+
}
765+
766+
zlistx_sort(list);
767+
768+
assert (zlistx_size (list) == nitems);
769+
assert (1 == *(int *) zlistx_first(list));
770+
assert (2 == *(int *) zlistx_next(list));
771+
assert (4 == *(int *) zlistx_next(list));
772+
assert (5 == *(int *) zlistx_next(list));
773+
assert (6 == *(int *) zlistx_next(list));
774+
assert (7 == *(int *) zlistx_next(list));
775+
assert (8 == *(int *) zlistx_next(list));
776+
assert (9 == *(int *) zlistx_next(list));
777+
assert (10 == *(int *) zlistx_next(list));
778+
assert (11 == *(int *) zlistx_next(list));
779+
780+
zlistx_destroy(&list);
781+
}
782+
744783
void
745784
zlistx_test (bool verbose)
746785
{
@@ -868,6 +907,8 @@ zlistx_test (bool verbose)
868907
zlistx_purge (list);
869908
zlistx_destroy (&list);
870909

910+
test_numeric_sort();
911+
871912
#if defined (__WINDOWS__)
872913
zsys_shutdown();
873914
#endif

0 commit comments

Comments
 (0)