Updating built in Io code to use += instead of x = x + y
[io/quag.git] / libs / basekit / source / Sorting.c
blob88e3411b31c3a4fe309f4131d24c513daa5ea0d0
1 #include "Sorting.h"
3 typedef struct
5 void *context;
6 SDSortCompareCallback *comp;
7 SDSortSwapCallback *swap;
8 } SDSort;
10 int Sorting_isSorted(SDSort *self, size_t size);
11 void Sorting_quickSort(SDSort *self, size_t lb, size_t ub);
12 int Sorting_quickSortRearrange(SDSort *self, size_t lb, size_t ub);
14 void Sorting_context_comp_swap_size_type_(void *context,
15 SDSortCompareCallback *comp,
16 SDSortSwapCallback *swap,
17 size_t size,
18 SDSortType type)
20 SDSort q;
21 SDSort *self = &q;
23 self->context = context;
24 self->comp = comp;
25 self->swap = swap;
27 switch (type)
29 case SDQuickSort:
30 if (!Sorting_isSorted(self, size)) Sorting_quickSort(self, 0, size-1);
31 break;
35 int Sorting_isSorted(SDSort *self, size_t size)
37 SDSortCompareCallback *comp = self->comp;
38 void *context = self->context;
39 size_t i;
41 for (i = 0; i + 1 < size; i ++)
43 if ((*comp)(context, i, i + 1) > 0)
45 return 0;
49 return 1;
52 void Sorting_quickSort(SDSort *self, size_t lb, size_t ub)
54 if (lb < ub)
56 int j = Sorting_quickSortRearrange(self, lb, ub);
58 if (j)
60 Sorting_quickSort(self, lb, j - 1);
63 Sorting_quickSort(self, j + 1, ub);
67 int Sorting_quickSortRearrange(SDSort *self, size_t lb, size_t ub)
69 SDSortCompareCallback *comp = self->comp;
70 SDSortSwapCallback *swap = self->swap;
71 void *context = self->context;
73 do {
74 while (ub > lb && (*comp)(context, ub, lb) >= 0)
76 ub --;
79 if (ub != lb)
81 (*swap)(context, ub, lb);
83 while (lb < ub && (*comp)(context, lb, ub) <= 0)
85 lb ++;
88 if (lb != ub)
90 (*swap)(context, lb, ub);
93 } while (lb != ub);
95 return lb;