emp-toolkit
number.h
Go to the documentation of this file.
1 #ifndef NUMBER_H__
2 #define NUMBER_H__
3 #include "bit.h"
4 
5 
6 template<typename T, typename D>
7 void cmp_swap(T*key, D*data, int i, int j, Bit acc) {
8  Bit to_swap = ((key[i] > key[j]) == acc);
9  swap(to_swap, key[i], key[j]);
10  if(data != nullptr)
11  swap(to_swap, data[i], data[j]);
12 }
13 
15  int k = 1;
16  while (k < n)
17  k = k << 1;
18  return k >> 1;
19 }
20 
21 template<typename T, typename D>
22 void bitonic_merge(T* key, D* data, int lo, int n, Bit acc) {
23  if (n > 1) {
24  int m = greatestPowerOfTwoLessThan(n);
25  for (int i = lo; i < lo + n - m; i++)
26  cmp_swap(key, data, i, i + m, acc);
27  bitonic_merge(key, data, lo, m, acc);
28  bitonic_merge(key, data, lo + m, n - m, acc);
29  }
30 }
31 
32 template<typename T, typename D>
33 void bitonic_sort(T * key, D * data, int lo, int n, Bit acc) {
34  if (n > 1) {
35  int m = n / 2;
36  bitonic_sort(key, data, lo, m, !acc);
37  bitonic_sort(key, data, lo + m, n - m, acc);
38  bitonic_merge(key, data, lo, n, acc);
39  }
40 }
41 
42 template <typename T, typename D = Bit>
43 void sort(T * key, int size, D* data = nullptr, Bit acc = true) {
44  bitonic_sort(key, data, 0, size, acc);
45 }
46 
47 #endif
void sort(T *key, int size, D *data=nullptr, Bit acc=true)
Definition: number.h:43
int greatestPowerOfTwoLessThan(int n)
Definition: number.h:14
void bitonic_sort(T *key, D *data, int lo, int n, Bit acc)
Definition: number.h:33
void bitonic_merge(T *key, D *data, int lo, int n, Bit acc)
Definition: number.h:22
void swap(const Bit &swap, T &o1, T &o2)
Definition: swappable.h:18
Definition: bit.h:8
void cmp_swap(T *key, D *data, int i, int j, Bit acc)
Definition: number.h:7