#ifndef _StableSort_QStableSort_h_ #define _StableSort_QStableSort_h_ template struct StableSortItem { const T& value; int index; StableSortItem(const T& value, int index) : value(value), index(index) {} }; template struct StableSortIterator { II ii; int *vi; typedef StableSortIterator Iter; Iter& operator ++ () { ++ii; ++vi; return *this; } Iter& operator -- () { --ii; --vi; return *this; } Iter operator + (int i) const { return Iter(ii + i, vi + i); } Iter operator - (int i) const { return Iter(ii - i, vi - i); } int operator - (Iter b) const { return (int)(ii - b.ii); } bool operator == (Iter b) const { return ii == b.ii; } bool operator != (Iter b) const { return ii != b.ii; } bool operator < (Iter b) const { return ii < b.ii; } StableSortItem operator*() const { return StableSortItem(*ii, *vi); } friend void IterSwap(Iter a, Iter b) { IterSwap(a.ii, b.ii); IterSwap(a.vi, b.vi); } StableSortIterator(II ii, int *vi) : ii(ii), vi(vi) {} }; template struct StableSortLessCmp { bool operator()(const StableSortItem& a, const StableSortItem& b) const { int q = SgnCompare(a.value, b.value); return q ? q < 0 : a.index < b.index; } }; template void QStableSortCmp(C& c) { Buffer h(c.GetCount()); for(int i = 0; i < c.GetCount(); i++) h[i] = i; Sort(StableSortIterator(c.Begin(), ~h), StableSortIterator(c.End(), ~h + c.GetCount()), StableSortLessCmp()); } template struct StableSortLess { bool operator()(const StableSortItem& a, const StableSortItem& b) const { if(a.value < b.value) return true; return b.value < a.value ? false : a.index < b.index; } }; template void QStableSort(C& c) { Buffer h(c.GetCount()); for(int i = 0; i < c.GetCount(); i++) h[i] = i; Sort(StableSortIterator(c.Begin(), ~h), StableSortIterator(c.End(), ~h + c.GetCount()), StableSortLess()); } #endif