2 * Copyright (C) 2011 Red Hat, Inc.
4 * SPDX-License-Identifier: LGPL-2.1-or-later
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
23 int_compare_data (gconstpointer p1, gconstpointer p2, gpointer data)
32 test_sort_basic (void)
37 data = g_malloc (10000 * sizeof (int));
38 for (i = 0; i < 10000; i++)
40 data[i] = g_random_int_range (0, 10000);
43 g_qsort_with_data (data, 10000, sizeof (int), int_compare_data, NULL);
45 for (i = 1; i < 10000; i++)
46 g_assert_cmpint (data[i -1], <=, data[i]);
52 test_sort_zero_elements (void)
54 gint *data, *data_copy;
57 data = g_malloc (100 * sizeof (int));
58 data_copy = g_malloc (100 * sizeof (int));
59 for (i = 0; i < 100; i++)
61 data[i] = g_random_int ();
62 data_copy[i] = data[i];
65 /* 0 elements is a valid case */
66 g_qsort_with_data (data, 0, sizeof (int), int_compare_data, NULL);
68 for (i = 0; i < 100; i++)
69 g_assert_cmpint (data[i], ==, data_copy[i]);
87 item_compare_data (gconstpointer p1, gconstpointer p2, gpointer data)
89 const SortItem *i1 = p1;
90 const SortItem *i2 = p2;
92 return i1->val - i2->val;
96 test_sort_stable (void)
101 data = g_malloc (10000 * sizeof (SortItem));
102 for (i = 0; i < 10000; i++)
104 data[i].val = g_random_int_range (0, 10000);
108 g_qsort_with_data (data, 10000, sizeof (SortItem), item_compare_data, NULL);
110 for (i = 1; i < 10000; i++)
112 g_assert_cmpint (data[i -1].val, <=, data[i].val);
113 if (data[i -1].val == data[i].val)
114 g_assert_cmpint (data[i -1].i, <, data[i].i);
125 data = g_malloc (10000 * sizeof (BigItem));
126 for (i = 0; i < 10000; i++)
128 data[i].val = g_random_int_range (0, 10000);
132 g_qsort_with_data (data, 10000, sizeof (BigItem), item_compare_data, NULL);
134 for (i = 1; i < 10000; i++)
136 g_assert_cmpint (data[i -1].val, <=, data[i].val);
137 if (data[i -1].val == data[i].val)
138 g_assert_cmpint (data[i -1].i, <, data[i].i);
144 main (int argc, char *argv[])
146 g_test_init (&argc, &argv, NULL);
148 g_test_add_func ("/sort/basic", test_sort_basic);
149 g_test_add_func ("/sort/zero-elements", test_sort_zero_elements);
150 g_test_add_func ("/sort/stable", test_sort_stable);
151 g_test_add_func ("/sort/big", test_sort_big);
153 return g_test_run ();