diff --git a/AK/QuickSort.h b/AK/QuickSort.h index 88ecd80623e..01834c6f8a5 100644 --- a/AK/QuickSort.h +++ b/AK/QuickSort.h @@ -2,44 +2,36 @@ namespace AK { -template -IteratorType partition(IteratorType first, IteratorType last, LessThan less_than) -{ - auto pivot = last; - auto smallest = first - 1; - auto it = first; - for (; it < last; ++it) { - if (less_than(*it, *pivot)) { - ++smallest; - swap(*it, *smallest); - } - } - swap(*(smallest + 1), *last); - return smallest + 1; -} - -template -void quick_sort_impl(IteratorType begin, IteratorType first, IteratorType last, LessThan less_than) -{ - if (first < last) { - auto pivot = partition(first, last, less_than); - quick_sort_impl(begin, first, pivot - 1, less_than); - quick_sort_impl(begin, pivot + 1, last, less_than); - } -} - template bool is_less_than(const T& a, const T& b) { return a < b; } -template -void quick_sort(IteratorType begin, IteratorType end, LessThan less_than = is_less_than) +template +void quick_sort(Iterator start, Iterator end, LessThan less_than = is_less_than) { - if (begin == end) + int size = end - start; + if (size <= 0) return; - quick_sort_impl(begin, begin, end - 1, less_than); + + int pivot_point = size / 2; + auto pivot = *(start + pivot_point); + + if (pivot_point) + swap(*(start + pivot_point), *start); + + int i = 1; + for (int j = 1; j < size; ++j) { + if (less_than(*(start + j), pivot)) { + swap(*(start+j), *(start + i)); + ++i; + } + } + + swap(*start, *(start + i - 1)); + quick_sort(start, start + i - 1, less_than); + quick_sort(start + i, end, less_than); } } diff --git a/AK/Vector.h b/AK/Vector.h index f3474b0ee81..be193eca0ad 100644 --- a/AK/Vector.h +++ b/AK/Vector.h @@ -316,6 +316,7 @@ public: Iterator operator-(int value) { return { m_vector, m_index - value }; } Iterator operator+(int value) { return { m_vector, m_index + value }; } T& operator*() { return m_vector[m_index]; } + int operator-(const Iterator& other) { return m_index - other.m_index; } private: friend class Vector; Iterator(Vector& vector, int index) : m_vector(vector), m_index(index) { } @@ -335,6 +336,7 @@ public: ConstIterator operator-(int value) { return { m_vector, m_index - value }; } ConstIterator operator+(int value) { return { m_vector, m_index + value }; } const T& operator*() const { return m_vector[m_index]; } + int operator-(const ConstIterator& other) { return m_index - other.m_index; } private: friend class Vector; ConstIterator(const Vector& vector, const int index) : m_vector(vector), m_index(index) { }