GraphChi 0.1

- Main Page
- Namespaces
- Classes
- Files

- File List
- File Members

All Classes Namespaces Files Functions Variables Typedefs Enumerations Macros
qsort.hpp
1 // This code is part of the Problem Based Benchmark Suite (PBBS)
2 // Copyright (c) 2010 Guy Blelloch and Harsha Vardhan Simhadri and the PBBS team
3 //
4 // Permission is hereby granted, free of charge, to any person obtaining a
5 // copy of this software and associated documentation files (the
6 // "Software"), to deal in the Software without restriction, including
7 // without limitation the rights (to use, copy, modify, merge, publish,
8 // distribute, sublicense, and/or sell copies of the Software, and to
9 // permit persons to whom the Software is furnished to do so, subject to
10 // the following conditions:
11 //
12 // The above copyright notice and this permission notice shall be included
13 // in all copies or substantial portions of the Software.
14 //
15 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
16 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22
23
24 #ifndef GRAPHCHI_QSORT_INCLUDED
25 #define GRAPHCHI_QSORT_INCLUDED
26
27 #include <algorithm>
28 #include <vector>
29
30 template <class E, class BinPred>
31 void insertionSort(E* A, int n, BinPred f) {
32 for (int i=0; i < n; i++) {
33 E v = A[i];
34 E* B = A + i;
35 while (--B >= A && f(v,*B)) *(B+1) = *B;
36 *(B+1) = v;
37 }
38 }
39
40
41 #define ISORT 25
42
43 template <class E, class BinPred>
44 E median(E a, E b, E c, BinPred f) {
45 return f(a,b) ? (f(b,c) ? b : (f(a,c) ? c : a))
46 : (f(a,c) ? a : (f(b,c) ? c : b));
47 }
48
49 // Partly copied from PBBS
50 template <class E, class BinPred>
51 void quickSort(E* A, int n, BinPred f) {
52 if (n < ISORT) insertionSort(A, n, f);
53 else {
54 E p = A[rand() % n]; // Random pivot
55 E* L = A; // below L are less than pivot
56 E* M = A; // between L and M are equal to pivot
57 E* R = A+n-1; // above R are greater than pivot
58 while (1) {
59 while (!f(p,*M)) {
60 if (f(*M,p)) std::swap(*M,*(L++));
61 if (M >= R) break;
62 M++;
63 }
64 while (f(p,*R)) R--;
65 if (M >= R) break;
66 std::swap(*M,*R--);
67 if (f(*M,p)) std::swap(*M,*(L++));
68 M++;
69 }
70 quickSort(A, (int) (L-A), f);
71 quickSort(M, (int) (A+n-M), f); // Exclude all elts that equal pivot
72 }
73 }
74
75
76 #endif
77