Elm  2
ELM is a library providing generic data structures, OS-independent interface, plugins and XML.
quicksort.h
1 /*
2  * quicksort implementation
3  *
4  * This file is part of OTAWA
5  * Copyright (c) 2004-08, IRIT UPS.
6  *
7  * OTAWA is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * OTAWA 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
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with OTAWA; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21 #ifndef ELM_QUICKSORT_H_
22 #define ELM_QUICKSORT_H_
23 
24 #include <elm/compare.h>
25 
26 namespace elm {
27 
28 // quick sort
29 template <class A, class C = Comparator<typename A::t> >
30 void quicksort(A& array, const C& c = Comparator<typename A::t>()) {
31  static const int max = 300;
32  int beg[max], end[max], i = 0, L, R, swap;
33  typename A::t piv;
34 
35  beg[0] = 0; end[0] = array.count();
36  while(i >= 0) {
37  L = beg[i]; R = end[i] - 1;
38  if(L < R) {
39  piv = array[L];
40  while(L < R) {
41  while(C::compare(array[R], piv) >= 0 && L < R) R--; if(L < R) array[L++] = array[R];
42  while(C::compare(array[L], piv) <= 0 && L<R) L++; if (L < R) array[R--] = array[L];
43  }
44  array[L] = piv; beg[i+1] = L+1; end[i+1] = end[i]; end[i++] = L;
45  if(end[i] - beg[i] > end[i-1] - beg[i-1]) {
46  swap = beg[i]; beg[i] = beg[i-1]; beg[i-1] = swap;
47  swap = end[i]; end[i] = end[i-1]; end[i-1] = swap;
48  }
49  }
50  else
51  i--;
52  }
53 }
54 
55 } // elm
56 
57 #endif /* ELM_QUICKSORT_H_ */
elm::max
const T & max(const T &x, const T &y)
Definition: compare.h:108
elm::quicksort
void quicksort(A &array, const C &c=Comparator< typename A::t >())
Definition: quicksort.h:30
elm
Definition: adapter.h:26
array
elm::Comparator
Definition: compare.h:34
elm::swap
void swap(T &x, T &y)
Definition: misc.h:27