鄙人目光短浅,以为见到的这个时间复杂度为O(n!)的排序是最慢的。如果不是,请举出更慢的例子:)
原理是枚举所有排列组合,直到找到一个合适的有序序列,取名蜗牛排序。
使用模板来实现。
1 template <typename T>
2 struct greater
3 {
4 bool operator()(const T& x, const T& y) const { return y < x; }
5 };
6
7 template <typename T>
8 struct less
9 {
10 bool operator()(const T& x, const T& y) const { return x < y; }
11 };
12
13 template <typename T>
14 inline void swap(T& x, T& y)
15 {
16 const T tmp(x);
17 x = y;
18 y = tmp;
19 }
20
21 // reverse a sequence in the range [first, last)
22 template <typename BidirectionalIter>
23 void reverse(BidirectionalIter first, BidirectionalIter last)
24 {
25 while(true)
26 if(first == last || first == --last)
27 return;
28 else
29 swap(*first++, *last);
30 }
31 // find the next possible permutation
32 template <typename BidirectionalIter, typename Compare>
33 bool next_permutation(BidirectionalIter first, BidirectionalIter last,
34 Compare cmp)
35 {
36 if(first == last)
37 return false;
38 BidirectionalIter i = first;
39 ++i;
40 if(i == last)
41 return false;
42 i = last;
43 --i;
44
45 for(;;)
46 {
47 BidirectionalIter ii = i;
48 --i;
49 if(cmp(*i, *ii))
50 {
51 BidirectionalIter j = last;
52 while(!cmp(*i, *--j));
53 swap(*i, *j);
54 reverse(ii, last);
55 return true;
56 }
57 if(i == first)
58 {
59 reverse(first, last);
60 return false;
61 }
62 }
63 }
64
65 template <typename BidirectionalIterator, typename Compare>
66 void snail_sort(BidirectionalIterator first, BidirectionalIterator last, Compare cmp)
67 {
68 while(next_permutation(first, last, cmp));
69 }
70
71 #include <iostream>
72
73 int main()
74 {
75 const int SZ = 12;
76 int arr[SZ] = { 5, 3, 9, 7, 4, 6, 5, 0, 2, 1, 3, 8 };
77 snail_sort(arr, arr + SZ, greater<int>());
78 for(int i =0 ; i < SZ; ++i)
79 std::cout << arr[i] << ' ';
80 }