libjmmcg  release_579_6_g8cffd
A C++ library containing an eclectic mix of useful, advanced components.
bogo_sort.hpp
Go to the documentation of this file.
1 #ifndef LIBJMMCG_CORE_BOGO_SORT_HPP
2 #define LIBJMMCG_CORE_BOGO_SORT_HPP
3 
4 /******************************************************************************
5 ** Copyright © 2004 by J.M.McGuiness, coder@hussar.me.uk
6 **
7 ** This library is free software; you can redistribute it and/or
8 ** modify it under the terms of the GNU Lesser General Public
9 ** License as published by the Free Software Foundation; either
10 ** version 2.1 of the License, or (at your option) any later version.
11 **
12 ** This library is distributed in the hope that it will be useful,
13 ** but WITHOUT ANY WARRANTY; without even the implied warranty of
14 ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 ** Lesser General Public License for more details.
16 **
17 ** You should have received a copy of the GNU Lesser General Public
18 ** License along with this library; if not, write to the Free Software
19 ** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 */
21 
22 #include "config.h"
23 
24 #include <algorithm>
25 
26 namespace jmmcg { namespace LIBJMMCG_VER_NAMESPACE {
27 
28  /// An implementation of the bogo-sort[1] algorithm, in STL-style.
29  /**
30  Apologies to all members of the C++ standards community for this perversion.
31  This algorithm should never be used in any code, apart from as an example of easy it is to create an apparently innocuous algorithm which can have an exceptionally bad order.
32 
33  I quote an edited excerpt of a discussion on the ACCU-General mailing list regarding this implementation:
34  "The quest for perversity was clearly at odds with the quest for beauty. I think perversity wins out in this case.
35 
36  And yes, you're a very bad man. How about compounding your badness and just writing this little gem up for Overload or blogging it so that it becomes immortalised and searchable? >:->
37 
38  Kevlin [Henney]"
39 
40  \param first The start of the input range.
41  \param last The end of the input range.
42  \param comp The comparator to be used to compare two values within the range.
43 
44  Complexity: the *truly* excessive and exorbitant: O(N*N!+N*N)=O(N*N!), c.f. with O(nlog(n)) of std::sort().
45 
46  [1] <a href="http://www.tcs.ifi.lmu.de/~gruberh/data/fun07-final.pdf"/>
47 
48  \see std::sort()
49  */
50  template<class Iter, class Compare> inline void FORCE_INLINE
51  bogo_sort(Iter first, Iter last, Compare comp) {
52  /*
53  Note that this technique (the suggester shall remain nameless to protect the innocent) is used:
54 
55  "The elegant beauty of
56  while(std::next_permutation(first, last));
57  is lost in your version.;-)"
58  */
59  while(std::next_permutation(first, last, comp));
60  }
61 
62 } }
63 
64 #endif