Merge branch '976-disable-assert-checks' into 'master'
[glib.git] / glib / tests / sort.c
blob7aa27c89569a5749e953cc86371faa844abf2790
1 /*
2 * Copyright (C) 2011 Red Hat, Inc.
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
18 #include <glib.h>
20 static int
21 int_compare_data (gconstpointer p1, gconstpointer p2, gpointer data)
23 const gint *i1 = p1;
24 const gint *i2 = p2;
26 return *i1 - *i2;
29 static void
30 test_sort_basic (void)
32 gint *data;
33 gint i;
35 data = g_malloc (10000 * sizeof (int));
36 for (i = 0; i < 10000; i++)
38 data[i] = g_random_int_range (0, 10000);
41 g_qsort_with_data (data, 10000, sizeof (int), int_compare_data, NULL);
43 for (i = 1; i < 10000; i++)
44 g_assert_cmpint (data[i -1], <=, data[i]);
46 g_free (data);
49 typedef struct {
50 int val;
51 int i;
52 } SortItem;
54 typedef struct {
55 int val;
56 int i;
57 int data[16];
58 } BigItem;
60 static int
61 item_compare_data (gconstpointer p1, gconstpointer p2, gpointer data)
63 const SortItem *i1 = p1;
64 const SortItem *i2 = p2;
66 return i1->val - i2->val;
69 static void
70 test_sort_stable (void)
72 SortItem *data;
73 gint i;
75 data = g_malloc (10000 * sizeof (SortItem));
76 for (i = 0; i < 10000; i++)
78 data[i].val = g_random_int_range (0, 10000);
79 data[i].i = i;
82 g_qsort_with_data (data, 10000, sizeof (SortItem), item_compare_data, NULL);
84 for (i = 1; i < 10000; i++)
86 g_assert_cmpint (data[i -1].val, <=, data[i].val);
87 if (data[i -1].val == data[i].val)
88 g_assert_cmpint (data[i -1].i, <, data[i].i);
90 g_free (data);
93 static void
94 test_sort_big (void)
96 BigItem *data;
97 gint i;
99 data = g_malloc (10000 * sizeof (BigItem));
100 for (i = 0; i < 10000; i++)
102 data[i].val = g_random_int_range (0, 10000);
103 data[i].i = i;
106 g_qsort_with_data (data, 10000, sizeof (BigItem), item_compare_data, NULL);
108 for (i = 1; i < 10000; i++)
110 g_assert_cmpint (data[i -1].val, <=, data[i].val);
111 if (data[i -1].val == data[i].val)
112 g_assert_cmpint (data[i -1].i, <, data[i].i);
114 g_free (data);
118 main (int argc, char *argv[])
120 g_test_init (&argc, &argv, NULL);
122 g_test_add_func ("/sort/basic", test_sort_basic);
123 g_test_add_func ("/sort/stable", test_sort_stable);
124 g_test_add_func ("/sort/big", test_sort_big);
126 return g_test_run ();