GNU Octave  9.1.0
A high-level interpreted language, primarily intended for numerical computations, mostly compatible with Matlab
oct-sort.h
Go to the documentation of this file.
1 ////////////////////////////////////////////////////////////////////////
2 //
3 // Copyright (C) 2003-2024 The Octave Project Developers
4 //
5 // See the file COPYRIGHT.md in the top-level directory of this
6 // distribution or <https://octave.org/copyright/>.
7 //
8 // This file is part of Octave.
9 //
10 // Octave is free software: you can redistribute it and/or modify it
11 // under the terms of the GNU General Public License as published by
12 // the Free Software Foundation, either version 3 of the License, or
13 // (at your option) any later version.
14 //
15 // Octave is distributed in the hope that it will be useful, but
16 // WITHOUT ANY WARRANTY; without even the implied warranty of
17 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 // GNU General Public License for more details.
19 //
20 // You should have received a copy of the GNU General Public License
21 // along with Octave; see the file COPYING. If not, see
22 // <https://www.gnu.org/licenses/>.
23 //
24 // Code stolen in large part from Python's, listobject.c, which itself had
25 // no license header. However, thanks to Tim Peters for the parts of the
26 // code I ripped-off.
27 //
28 // As required in the Python license the short description of the changes
29 // made are
30 //
31 // * convert the sorting code in listobject.cc into a generic class,
32 // replacing PyObject* with the type of the class T.
33 //
34 // The Python license is
35 //
36 // PSF LICENSE AGREEMENT FOR PYTHON 2.3
37 // --------------------------------------
38 //
39 // 1. This LICENSE AGREEMENT is between the Python Software Foundation
40 // ("PSF"), and the Individual or Organization ("Licensee") accessing and
41 // otherwise using Python 2.3 software in source or binary form and its
42 // associated documentation.
43 //
44 // 2. Subject to the terms and conditions of this License Agreement, PSF
45 // hereby grants Licensee a nonexclusive, royalty-free, world-wide
46 // license to reproduce, analyze, test, perform and/or display publicly,
47 // prepare derivative works, distribute, and otherwise use Python 2.3
48 // alone or in any derivative version, provided, however, that PSF's
49 // License Agreement and PSF's notice of copyright, i.e., "Copyright (c)
50 // 2001, 2002, 2003 Python Software Foundation; All Rights Reserved" are
51 // retained in Python 2.3 alone or in any derivative version prepared by
52 // Licensee.
53 //
54 // 3. In the event Licensee prepares a derivative work that is based on
55 // or incorporates Python 2.3 or any part thereof, and wants to make
56 // the derivative work available to others as provided herein, then
57 // Licensee hereby agrees to include in any such work a brief summary of
58 // the changes made to Python 2.3.
59 //
60 // 4. PSF is making Python 2.3 available to Licensee on an "AS IS"
61 // basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
62 // IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND
63 // DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
64 // FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 2.3 WILL NOT
65 // INFRINGE ANY THIRD PARTY RIGHTS.
66 //
67 // 5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
68 // 2.3 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
69 // A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 2.3,
70 // OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
71 //
72 // 6. This License Agreement will automatically terminate upon a material
73 // breach of its terms and conditions.
74 //
75 // 7. Nothing in this License Agreement shall be deemed to create any
76 // relationship of agency, partnership, or joint venture between PSF and
77 // Licensee. This License Agreement does not grant permission to use PSF
78 // trademarks or trade name in a trademark sense to endorse or promote
79 // products or services of Licensee, or any third party.
80 //
81 // 8. By copying, installing or otherwise using Python 2.3, Licensee
82 // agrees to be bound by the terms and conditions of this License
83 // Agreement.
84 //
85 ////////////////////////////////////////////////////////////////////////
86 
87 #if ! defined (octave_oct_sort_h)
88 #define octave_oct_sort_h 1
89 
90 #include "octave-config.h"
91 
92 #include <functional>
93 
94 #include "lo-traits.h"
95 
96 // Enum for type of sort function
98 
99 template <typename T>
100 class
101 OCTAVE_TEMPLATE_API
103 {
104 public:
105 
106  typedef std::function<bool (typename ref_param<T>::type,
108 
109  octave_sort ();
110 
111  octave_sort (const compare_fcn_type&);
112 
113  OCTAVE_DISABLE_COPY_MOVE (octave_sort)
114 
115  ~octave_sort ();
116 
117  void set_compare (const compare_fcn_type& comp) { m_compare = comp; }
118 
119  void set_compare (sortmode mode);
120 
121  // Sort an array in-place.
122  void sort (T *data, octave_idx_type nel);
123 
124  // Ditto, but also permute the passed indices (may not be valid indices).
125  void sort (T *data, octave_idx_type *idx, octave_idx_type nel);
126 
127  // Check whether an array is sorted.
128  bool issorted (const T *data, octave_idx_type nel);
129 
130  // Sort a matrix by rows, return a permutation
131  // vector.
132  void sort_rows (const T *data, octave_idx_type *idx,
133  octave_idx_type rows, octave_idx_type cols);
134 
135  // Determine whether a matrix (as a contiguous block) is sorted by rows.
136  bool is_sorted_rows (const T *data,
137  octave_idx_type rows, octave_idx_type cols);
138 
139  // Do a binary lookup in a sorted array.
140  octave_idx_type lookup (const T *data, octave_idx_type nel,
141  const T& value);
142 
143  // Ditto, but for an array.
144  void lookup (const T *data, octave_idx_type nel,
145  const T *values, octave_idx_type nvalues,
146  octave_idx_type *idx);
147 
148  // A linear merge of two sorted tables. rev indicates the second table is
149  // in reverse order.
150  void lookup_sorted (const T *data, octave_idx_type nel,
151  const T *values, octave_idx_type nvalues,
152  octave_idx_type *idx, bool rev = false);
153 
154  // Rearranges the array so that the elements with indices
155  // lo..up-1 are in their correct place.
156  void nth_element (T *data, octave_idx_type nel,
157  octave_idx_type lo, octave_idx_type up = -1);
158 
159  static bool ascending_compare (typename ref_param<T>::type,
160  typename ref_param<T>::type);
161 
162  static bool descending_compare (typename ref_param<T>::type,
163  typename ref_param<T>::type);
164 
165 private:
166 
167  // The maximum number of entries in a MergeState's pending-runs stack.
168  // This is enough to sort arrays of size up to about
169  // 32 * phi ** MAX_MERGE_PENDING
170  // where phi ~= 1.618. 85 is ridiculously large enough, good for an array
171  // with 2^64 elements.
172  static const int MAX_MERGE_PENDING = 85;
173 
174  // When we get into galloping mode, we stay there until both runs win less
175  // often than MIN_GALLOP consecutive times. See listsort.txt for more info.
176  static const int MIN_GALLOP = 7;
177 
178  // Avoid malloc for small temp arrays.
179  static const int MERGESTATE_TEMP_SIZE = 1024;
180 
181  // One MergeState exists on the stack per invocation of mergesort.
182  // It's just a convenient way to pass state around among the helper
183  // functions.
184  //
185  // DGB: This isn't needed with mergesort in a class, but it doesn't
186  // slow things up, and it is likely to make my life easier for any
187  // potential backporting of changes in the Python code.
188 
189  struct s_slice
190  {
191  octave_idx_type m_base, m_len;
192  };
193 
194  struct MergeState
195  {
196  public:
197 
198  MergeState ()
199  : m_min_gallop (), m_a (nullptr), m_ia (nullptr), m_alloced (0), m_n (0)
200  { reset (); }
201 
202  OCTAVE_DISABLE_COPY_MOVE (MergeState)
203 
204  ~MergeState ()
205  { delete [] m_a; delete [] m_ia; }
206 
207  void reset ()
208  { m_min_gallop = MIN_GALLOP; m_n = 0; }
209 
210  void getmem (octave_idx_type need);
211 
212  void getmemi (octave_idx_type need);
213 
214  //--------
215 
216  // This controls when we get *into* galloping mode. It's initialized to
217  // MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for random
218  // data, and lower for highly structured data.
219  octave_idx_type m_min_gallop;
220 
221  // 'a' is temp storage to help with merges. It contains room for
222  // alloced entries.
223  T *m_a; // may point to temparray below
224  octave_idx_type *m_ia;
225  octave_idx_type m_alloced;
226 
227  // A stack of n pending runs yet to be merged. Run #i starts at address
228  // base[i] and extends for len[i] elements. It's always true (so long as
229  // the indices are in bounds) that
230  //
231  // pending[i].base + pending[i].len == pending[i+1].base
232  //
233  // so we could cut the storage for this, but it's a minor amount,
234  // and keeping all the info explicit simplifies the code.
235  octave_idx_type m_n;
236  struct s_slice m_pending[MAX_MERGE_PENDING];
237  };
238 
239  compare_fcn_type m_compare;
240 
241  MergeState *m_ms;
242 
243  template <typename Comp>
244  void binarysort (T *data, octave_idx_type nel,
245  octave_idx_type start, Comp comp);
246 
247  template <typename Comp>
248  void binarysort (T *data, octave_idx_type *idx, octave_idx_type nel,
249  octave_idx_type start, Comp comp);
250 
251  template <typename Comp>
252  octave_idx_type count_run (T *lo, octave_idx_type n, bool& descending,
253  Comp comp);
254 
255  template <typename Comp>
256  octave_idx_type gallop_left (T key, T *a, octave_idx_type n,
257  octave_idx_type hint, Comp comp);
258 
259  template <typename Comp>
260  octave_idx_type gallop_right (T key, T *a, octave_idx_type n,
261  octave_idx_type hint, Comp comp);
262 
263  template <typename Comp>
264  int merge_lo (T *pa, octave_idx_type na,
265  T *pb, octave_idx_type nb,
266  Comp comp);
267 
268  template <typename Comp>
269  int merge_lo (T *pa, octave_idx_type *ipa, octave_idx_type na,
270  T *pb, octave_idx_type *ipb, octave_idx_type nb,
271  Comp comp);
272 
273  template <typename Comp>
274  int merge_hi (T *pa, octave_idx_type na,
275  T *pb, octave_idx_type nb,
276  Comp comp);
277 
278  template <typename Comp>
279  int merge_hi (T *pa, octave_idx_type *ipa, octave_idx_type na,
280  T *pb, octave_idx_type *ipb, octave_idx_type nb,
281  Comp comp);
282 
283  template <typename Comp>
284  int merge_at (octave_idx_type i, T *data, Comp comp);
285 
286  template <typename Comp>
287  int merge_at (octave_idx_type i, T *data, octave_idx_type *idx, Comp comp);
288 
289  template <typename Comp>
290  int merge_collapse (T *data, Comp comp);
291 
292  template <typename Comp>
293  int merge_collapse (T *data, octave_idx_type *idx, Comp comp);
294 
295  template <typename Comp>
296  int merge_force_collapse (T *data, Comp comp);
297 
298  template <typename Comp>
299  int merge_force_collapse (T *data, octave_idx_type *idx, Comp comp);
300 
301  octave_idx_type merge_compute_minrun (octave_idx_type n);
302 
303  template <typename Comp>
304  void sort (T *data, octave_idx_type nel, Comp comp);
305 
306  template <typename Comp>
307  void sort (T *data, octave_idx_type *idx, octave_idx_type nel, Comp comp);
308 
309  template <typename Comp>
310  bool issorted (const T *data, octave_idx_type nel, Comp comp);
311 
312  template <typename Comp>
313  void sort_rows (const T *data, octave_idx_type *idx,
314  octave_idx_type rows, octave_idx_type cols,
315  Comp comp);
316 
317  template <typename Comp>
318  bool is_sorted_rows (const T *data, octave_idx_type rows,
319  octave_idx_type cols, Comp comp);
320 
321  template <typename Comp>
322  octave_idx_type lookup (const T *data, octave_idx_type nel,
323  const T& value, Comp comp);
324 
325  template <typename Comp>
326  void lookup (const T *data, octave_idx_type nel,
327  const T *values, octave_idx_type nvalues,
328  octave_idx_type *idx, Comp comp);
329 
330  template <typename Comp>
331  void lookup_sorted (const T *data, octave_idx_type nel,
332  const T *values, octave_idx_type nvalues,
333  octave_idx_type *idx, bool rev, Comp comp);
334 
335  template <typename Comp>
336  void nth_element (T *data, octave_idx_type nel,
338  Comp comp);
339 };
340 
341 template <typename T>
342 class
343 OCTAVE_TEMPLATE_API
344 vec_index
345 {
346 public:
347  T m_vec;
349 };
350 
351 #endif
octave_idx_type lookup(const T *x, octave_idx_type n, T y)
void set_compare(const compare_fcn_type &comp)
Definition: oct-sort.h:117
std::function< bool(typename ref_param< T >::type, typename ref_param< T >::type)> compare_fcn_type
Definition: oct-sort.h:107
if_then_else< is_class_type< T >::no, T, T const & >::result type
Definition: lo-traits.h:121
octave_idx_type m_indx
Definition: oct-sort.h:348
octave_idx_type n
Definition: mx-inlines.cc:761
sortmode
Definition: oct-sort.h:97
@ UNSORTED
Definition: oct-sort.h:97
@ ASCENDING
Definition: oct-sort.h:97
@ DESCENDING
Definition: oct-sort.h:97