Cuda battery library
Loading...
Searching...
No Matches
algorithm.hpp
Go to the documentation of this file.
1// Copyright 2021 Pierre Talbot, Frédéric Pinel
2
3#ifndef CUDA_BATTERY_ALGORITHM_HPP
4#define CUDA_BATTERY_ALGORITHM_HPP
5
6#include "utility.hpp"
7#include "vector.hpp"
8#include "tuple.hpp"
9
10namespace battery {
11
12namespace impl {
13
14template <class Seq, class Compare>
15CUDA int partition(Seq& seq, int low, int high, Compare comp) {
16 int i = low - 1; // Index of smaller element
17
18 for (int j = low; j <= high - 1; j++) {
19 // If current element is smaller than the pivot
20 if (comp(j, high)) {
21 i++; // Increment index of smaller element
22 ::battery::swap(seq[i], seq[j]);
23 }
24 }
25 ::battery::swap(seq[i + 1], seq[high]);
26 return i + 1;
27}
28
29template <class Seq, class Compare>
30CUDA void quickSort(Seq& seq, Compare comp) {
31 if(seq.size() < 2) {
32 return;
33 }
34 vector<int> stackl;
35 vector<int> stackh;
36 stackl.push_back(0);
37 stackh.push_back(seq.size() - 1);
38 while(stackl.size() > 0) {
39 int low = stackl.back(); stackl.pop_back();
40 int high = stackh.back(); stackh.pop_back();
41 if(low < high) {
42 // pi is partitioning index, seq[p] is now at right place
43 int pi = partition(seq, low, high, comp);
44 // Separately sort elements before partition and after partition
45 // quickSort(seq, low, pi - 1, comp);
46 stackl.push_back(low);
47 stackh.push_back(pi-1);
48 // quickSort(seq, pi + 1, high, comp);
49 stackl.push_back(pi+1);
50 stackh.push_back(high);
51 }
52 }
53}
54}// namespace impl
55
56/** Sort the sequence `seq` in-place.
57 * The underlying algorithm is an iterative version of quicksort.
58 * * `comp(a, b)` returns `true` whenever a < b, and false otherwise. */
59template <class Seq, class Compare>
60CUDA NI void sort(Seq& seq, Compare comp) {
61 assert(seq.size() < limits<int>::inf());
62 impl::quickSort(seq, [&](int i, int j) { return comp(seq[i], seq[j]); });
63}
64
65/** Similar to `sort`, but the comparison function is takes indexes instead of elements themselves.
66 * * `comp(i, j)` returns `true` whenever seq[i] < seq[j], and false otherwise. */
67template <class Seq, class Compare>
68CUDA NI void sorti(Seq& seq, Compare comp) {
69 assert(seq.size() < limits<int>::inf());
70 impl::quickSort(seq, comp);
71}
72
73} // namespace battery
74
75#endif
Definition vector.hpp:20
CUDA void push_back(const T &value)
Definition vector.hpp:248
CUDA void pop_back()
Definition vector.hpp:273
CUDA size_t size() const
Definition vector.hpp:235
CUDA value_type & back()
Definition vector.hpp:230
Definition algorithm.hpp:10
CUDA constexpr void swap(T &a, T &b)
Definition utility.hpp:91
CUDA NI void sort(Seq &seq, Compare comp)
Definition algorithm.hpp:60
CUDA NI void sorti(Seq &seq, Compare comp)
Definition algorithm.hpp:68
Definition utility.hpp:177
#define CUDA
Definition utility.hpp:59
#define NI
Definition utility.hpp:62