Euphoria
quicksort.h
Go to the documentation of this file.
1 #pragma once
2 
3 
4 
5 
6 #include "base/cint.h"
7 
8 
9 namespace eu::core
10 {
11  // Hoare partition scheme as described in wikipedia
12  // https://en.wikipedia.org/wiki/Quicksort
13  template <typename T, typename TSortFunc>
14  int
15  get_hoare_partition(TSortFunc sort_func, std::vector<T>& array, int lo, int hi)
16  {
17  const auto pivot_index = lo + (hi - lo) / 2;
18  const auto pivot = array[pivot_index];
19  auto i = lo - 1;
20  auto j = hi + 1;
21  while(true)
22  {
23  do
24  {
25  i += 1;
26  } while(sort_func(array[i], pivot) < 0);
27  do
28  {
29  j -= 1;
30  } while(sort_func(array[j], pivot) > 0);
31 
32  if(i >= j)
33  {
34  return j;
35  }
36  std::swap(array[i], array[j]);
37  }
38  }
39 
40 
41  template <typename T, typename TSortFunc>
42  void
43  do_inplace_quick_sort_impl(TSortFunc sort_func, std::vector<T>& array, int lo, int hi)
44  {
45  if(lo < hi)
46  {
47  const auto p = get_hoare_partition(sort_func, array, lo, hi);
48  do_inplace_quick_sort_impl(sort_func, array, lo, p);
49  do_inplace_quick_sort_impl(sort_func, array, p + 1, hi);
50  }
51  }
52 
53  template <typename T, typename TSortFunc>
54  void
55  do_inplace_quick_sort(std::vector<T>* array, TSortFunc sort_func)
56  {
57  do_inplace_quick_sort_impl<T, TSortFunc>(sort_func, *array, 0, c_sizet_to_int(array->size()) - 1);
58  }
59 
60  template <typename T, typename TSortFunc>
61  std::vector<T>
62  get_quick_sorted(const std::vector<T>& arr, TSortFunc sort_func)
63  {
64  auto copy = arr;
65  do_inplace_quick_sort(&copy, sort_func);
66  return copy;
67  }
68 
69  template <typename T>
70  int
71  default_compare_for_quicksort(const T& lhs, const T& rhs)
72  {
73  if(lhs == rhs)
74  {
75  return 0;
76  }
77  return lhs < rhs ? -1 : 1;
78  }
79 
80  template <typename T>
81  std::vector<T>
82  get_quick_sorted(const std::vector<T>& arr)
83  {
84  return get_quick_sorted(arr, default_compare_for_quicksort<T>);
85  }
86 
87 }
88 
void copy(char *dst, const std::string &src, const std::string::size_type &count)
Copy a string to a character buffer, adding null terminator at the end.
Definition: stringutils.cc:293
int get_hoare_partition(TSortFunc sort_func, std::vector< T > &array, int lo, int hi)
Definition: quicksort.h:15
int default_compare_for_quicksort(const T &lhs, const T &rhs)
Definition: quicksort.h:71
void do_inplace_quick_sort_impl(TSortFunc sort_func, std::vector< T > &array, int lo, int hi)
Definition: quicksort.h:43
void do_inplace_quick_sort(std::vector< T > *array, TSortFunc sort_func)
Definition: quicksort.h:55
std::vector< T > get_quick_sorted(const std::vector< T > &arr, TSortFunc sort_func)
Definition: quicksort.h:62
constexpr StringMerger array
Definition: stringmerger.h:91
int c_sizet_to_int(size_t t)
Definition: cint.cc:11