Work on rstl::sort

This commit is contained in:
Henrique Gemignani Passos Lima
2022-11-27 05:04:19 +02:00
parent 318c1e0b7f
commit d95736167d
8 changed files with 134 additions and 23 deletions

View File

@@ -23,11 +23,81 @@ inline void iter_swap(I1 a, I2 b) {
swap(*a, *b);
}
template < class It, class Cmp >
void __sort3(It a, It b, It c, Cmp comp); // TODO
template < typename It, class Cmp >
void __insertion_sort(It first, It last, Cmp cmp);
template < class T, class Cmp >
void __sort3(T& a, T& b, T& c, Cmp comp); // TODO
template < typename It, class Cmp >
inline void sort(It first, It last, Cmp cmp); // TODO
void sort(It first, It last, Cmp cmp); // TODO
// Implementations
template < typename It, class Cmp >
void __insertion_sort(It first, It last, Cmp cmp) {
for (It next = first + 1; next < last; ++next) {
typename iterator_traits< It >::value_type value = *next;
It t1 = next;
It t2 = next;
while (first < t1 && cmp(value, *(t2 - 1))) {
*t1 = *(t2 - 1);
--t1;
--t2;
}
*t1 = value;
}
}
template < typename T, class Cmp >
void __sort3(T& a, T& b, T& c, Cmp comp) {
if (comp(b, a)) {
swap(a, b);
}
if (comp(c, b)) {
T tmp(c);
c = b;
if (comp(tmp, a)) {
b = a;
a = tmp;
} else {
b = tmp;
}
}
}
template < typename It, class Cmp >
void sort(It first, It last, Cmp cmp) {
int count = last - first;
if (count > 1) {
if (count <= 20) {
__insertion_sort(first, last, cmp);
} else {
It beforeLast = last - 1;
__sort3(*first, *(first + count / 2), *(last - 1), cmp);
It middle = first + count / 2;
It it = first + 1;
while (true) {
for (; cmp(*it, *middle); ++it)
;
for (; cmp(*middle, *beforeLast); --beforeLast)
;
if (!cmp(*it, *beforeLast))
break;
rstl::swap(*it, *beforeLast);
++it;
--beforeLast;
}
sort(first, it, cmp);
sort(it, last, cmp);
}
}
}
} // namespace rstl
#endif // _RSTL_ALGORITHM

View File

@@ -14,7 +14,7 @@ class const_pointer_iterator {
public:
typedef ptrdiff_t difference_type;
typedef random_access_iterator_tag iterator_category;
typedef T* value_type;
typedef T value_type;
const_pointer_iterator() : current(nullptr) {}
const_pointer_iterator(const T* begin) : current(const_cast< T* >(begin)) {}
@@ -133,6 +133,19 @@ inline typename It::difference_type __distance(It first, It last, random_access_
}
template < typename T >
struct iterator_traits {};
template < typename T >
struct iterator_traits<T*> {
typedef T value_type;
};
template < typename T, typename Vec, typename Alloc >
struct iterator_traits< pointer_iterator<T, Vec, Alloc> > {
typedef typename pointer_iterator<T, Vec, Alloc>::value_type value_type;
};
} // namespace rstl
#endif // _RSTL_POINTER_ITERATOR