# sort_func.hpp

Go to the documentation of this file.

    00001 /* $Id$ */
    00002
    00003 /*
    00004  * This file is part of OpenTTD.
    00005  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
    00006  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
    00007  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
    00008  */
    00009
    00012 #ifndef SORT_FUNC_HPP
    00013 #define SORT_FUNC_HPP
    00014
    00015 #include "mem_func.hpp"
    00016
    00027 template <typename T>
    00028 static inline void QSortT(T *base, uint num, int (CDECL *comparator)(const T*, const T*), bool desc = false)
    00029 {
    00030   if (num < 2) return;
    00031
    00032   qsort(base, num, sizeof(T), (int (CDECL *)(const void *, const void *))comparator);
    00033
    00034   if (desc) MemReverseT(base, num);
    00035 }
    00036
    00051 template <typename T>
    00052 static inline void GSortT(T *base, uint num, int (CDECL *comparator)(const T*, const T*), bool desc = false)
    00053 {
    00054   if (num < 2) return;
    00055
    00056   assert(base != NULL);
    00057   assert(comparator != NULL);
    00058
    00059   T *a = base;
    00060   T *b = base + 1;
    00061   uint offset = 0;
    00062
    00063   while (num > 1) {
    00064     const int diff = comparator(a, b);
    00065     if ((!desc && diff <= 0) || (desc && diff >= 0)) {
    00066       if (offset != 0) {
    00067         /* Jump back to the last direction switch point */
    00068         a += offset;
    00069         b += offset;
    00070         offset = 0;
    00071         continue;
    00072       }
    00073
    00074       a++;
    00075       b++;
    00076       num--;
    00077     } else {
    00078       Swap(*a, *b);
    00079
    00080       if (a == base) continue;
    00081
    00082       a--;
    00083       b--;
    00084       offset++;
    00085     }
    00086   }
    00087 }
    00088
    00089 #endif /* SORT_FUNC_HPP */