blob: 44342e0f46f709152068991db21a2e76ef4cf1cc [file] [log] [blame]
caryclark@google.comc6825902012-02-03 22:07:47 +00001#include "SkTypes.h"
2
3// FIXME: Move this templated version into SKTSearch.h
4
5template <typename T>
6static void QSort_Partition(T** first, T** last)
7{
8 T** left = first;
9 T** rite = last;
10 T** pivot = left;
11
12 while (left <= rite) {
13 while (left < last && **left < **pivot)
14 left += 1;
15 while (first < rite && **pivot < **rite)
16 rite -= 1;
17 if (left <= rite) {
18 if (left < rite) {
19 SkTSwap(*left, *rite);
20 }
21 left += 1;
22 rite -= 1;
23 }
24 }
25 if (first < rite)
26 QSort_Partition(first, rite);
27 if (left < last)
28 QSort_Partition(left, last);
29}
30
31template <typename T>
32void QSort(T** base, size_t count)
33{
34 SkASSERT(base);
35
36 if (count <= 1) {
37 return;
38 }
39 QSort_Partition(base, base + (count - 1));
40}
41
caryclark@google.comf8b000d2012-02-09 22:04:27 +000042template <typename S, typename T>
caryclark@google.comcef7e3f2012-02-28 16:57:05 +000043static T* QSort_Partition(S& context, T* left, T* right, T* pivot,
44 bool (*lessThan)(S&, const T, const T))
caryclark@google.comc6825902012-02-03 22:07:47 +000045{
caryclark@google.comcef7e3f2012-02-28 16:57:05 +000046 T pivotValue = *pivot;
47 SkTSwap(*pivot, *right);
48 T* newPivot = left;
49 while (left < right) {
50 if (lessThan(context, *left, pivotValue)) {
51 SkTSwap(*left, *newPivot);
52 newPivot += 1;
caryclark@google.comc6825902012-02-03 22:07:47 +000053 }
caryclark@google.comcef7e3f2012-02-28 16:57:05 +000054 left += 1;
caryclark@google.comc6825902012-02-03 22:07:47 +000055 }
caryclark@google.comcef7e3f2012-02-28 16:57:05 +000056 SkTSwap(*newPivot, *right);
57 return newPivot;
caryclark@google.comc6825902012-02-03 22:07:47 +000058}
59
caryclark@google.comf8b000d2012-02-09 22:04:27 +000060template <typename S, typename T>
caryclark@google.comcef7e3f2012-02-28 16:57:05 +000061void QSort(S& context, T* left, T* right,
62 bool (*lessThan)(S& , const T, const T))
caryclark@google.comc6825902012-02-03 22:07:47 +000063{
caryclark@google.comcef7e3f2012-02-28 16:57:05 +000064 if (left >= right) {
caryclark@google.comc6825902012-02-03 22:07:47 +000065 return;
66 }
caryclark@google.comcef7e3f2012-02-28 16:57:05 +000067 T* pivot = left + (right - left >> 1);
68 pivot = QSort_Partition(context, left, right, pivot, lessThan);
69 QSort(context, left, pivot - 1, lessThan);
70 QSort(context, pivot + 1, right, lessThan);
caryclark@google.comc6825902012-02-03 22:07:47 +000071}