Imported the initial C files that make up a decent sorting network toolkit already.
[sort-networks.git] / src / sn_comparator.c
1 #include <stdlib.h>
2 #include <string.h>
3
4 #include "sn_comparator.h"
5
6 sn_comparator_t *sn_comparator_create (int min, int max)
7 {
8   sn_comparator_t *c;
9
10   c = (sn_comparator_t *) malloc (sizeof (sn_comparator_t));
11   if (c == NULL)
12     return (NULL);
13   memset (c, '\0', sizeof (sn_comparator_t));
14
15   c->min = min;
16   c->max = max;
17
18   return (c);
19 } /* sn_comparator_t *sn_comparator_create */
20
21 void sn_comparator_destroy (sn_comparator_t *c)
22 {
23   if (c != NULL)
24     free (c);
25 } /* void sn_comparator_destroy */
26
27 void sn_comparator_invert (sn_comparator_t *c)
28 {
29   int max = c->min;
30   int min = c->max;
31
32   c->min = min;
33   c->max = max;
34 } /* void sn_comparator_invert */
35
36 void sn_comparator_swap (sn_comparator_t *c, int con0, int con1)
37 {
38   if (c->min == con0)
39   {
40     c->min = con1;
41   }
42   else if (c->min == con1)
43   {
44     c->min = con0;
45   }
46
47   if (c->max == con0)
48   {
49     c->max = con1;
50   }
51   else if (c->max == con1)
52   {
53     c->max = con0;
54   }
55 } /* void sn_comparator_swap */
56
57 int sn_comparator_compare (const void *v0, const void *v1)
58 {
59   sn_comparator_t *c0 = (sn_comparator_t *) v0;
60   sn_comparator_t *c1 = (sn_comparator_t *) v1;
61
62   if (SN_COMP_LEFT (c0) < SN_COMP_LEFT (c1))
63     return (-1);
64   else if (SN_COMP_LEFT (c0) > SN_COMP_LEFT (c1))
65     return (1);
66   else if (SN_COMP_RIGHT (c0) < SN_COMP_RIGHT (c1))
67     return (-1);
68   else if (SN_COMP_RIGHT (c0) > SN_COMP_RIGHT (c1))
69     return (1);
70   else
71     return (0);
72 } /* int sn_comparator_compare */
73
74 /* vim: set shiftwidth=2 softtabstop=2 : */