Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Merge branch 'master' of github.com:simgrid/simgrid into s_type_cleanup
[simgrid.git] / include / xbt / algorithm.hpp
1 /* Copyright (c) 2015-2017. The SimGrid Team. All rights reserved.          */
2
3 /* This program is free software; you can redistribute it and/or modify it
4  * under the terms of the license (GNU LGPL) which comes with this package. */
5
6 #ifndef XBT_ALGORITHM_HPP
7 #define XBT_ALGORITHM_HPP
8
9 namespace simgrid {
10 namespace xbt {
11
12 /** @brief Sorts the elements of the sequence [first, last) according to their color assuming elements can have only
13  * three colors.  Since there are only three colors, it is linear and much faster than a classical sort.  See for
14  * example http://en.wikipedia.org/wiki/Dutch_national_flag_problem
15  *
16  * \param first forward iterators to the initial position of the sequence to partition.
17  * \param last forward iterators to the final position of the sequence to partition.
18  * \param color the color function that accepts an element in the range as argument, and returns a value of 0, 1, or 2.
19  *
20  * At the end of the call, elements with color 0 are at the beginning of the range, elements with color 2 are at the end
21  * and elements with color 1 are in the middle.
22  */
23 template <class ForwardIterator, class ColorFunction>
24 void three_way_partition(ForwardIterator first, ForwardIterator last, ColorFunction color)
25 {
26   ForwardIterator iter = first;
27   while (iter < last) {
28     int c = color(*iter);
29     if (c == 1) {
30       ++iter;
31     } else if (c == 0) {
32       if (iter != first)
33         std::swap(*iter, *first);
34       ++iter;
35       ++first;
36     } else { // c == 2
37       --last;
38       if (iter != last)
39         std::swap(*iter, *last);
40     }
41   }
42 }
43 }
44 }
45
46 #endif