mirror of
https://github.com/SerenityOS/serenity.git
synced 2025-01-22 17:31:58 -05:00
AK: Fix InsertionSort to respect specified bounds
Previously, it ignored 'start', sorting from the array's beginning. This caused unintended changes and slower performance. Fix ensures sorting stays within 'start' and 'end' indices only. (cherry picked from commit 356016c626546aeb51722fe9ca5bb6a769bfe762)
This commit is contained in:
parent
141dfc53c2
commit
4f6f65d1f9
2 changed files with 24 additions and 1 deletions
|
@ -17,7 +17,7 @@ void insertion_sort(Collection& col, ssize_t start, ssize_t end, Comparator comp
|
||||||
requires(Indexable<Collection, T>)
|
requires(Indexable<Collection, T>)
|
||||||
{
|
{
|
||||||
for (ssize_t i = start + 1; i <= end; ++i) {
|
for (ssize_t i = start + 1; i <= end; ++i) {
|
||||||
for (ssize_t j = i; j > 0 && comparator(col[j], col[j - 1]); --j)
|
for (ssize_t j = i; j > start && comparator(col[j], col[j - 1]); --j)
|
||||||
swap(col[j], col[j - 1]);
|
swap(col[j], col[j - 1]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -55,3 +55,26 @@ TEST_CASE(sorts_decending)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
TEST_CASE(sorts_subrange_without_affecting_outside_elements)
|
||||||
|
{
|
||||||
|
Vector<int> ints = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };
|
||||||
|
Vector<int> const original_ints = ints;
|
||||||
|
|
||||||
|
ssize_t const start = 3;
|
||||||
|
ssize_t const end = 6;
|
||||||
|
|
||||||
|
insertion_sort(ints, start, end, [](auto& a, auto& b) { return a < b; });
|
||||||
|
|
||||||
|
for (ssize_t i = start; i < end; ++i) {
|
||||||
|
EXPECT(ints[i] <= ints[i + 1]);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (ssize_t i = 0; i < start; ++i) {
|
||||||
|
EXPECT_EQ(ints[i], original_ints[i]);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (ssize_t i = end + 1; i < static_cast<ssize_t>(ints.size()); ++i) {
|
||||||
|
EXPECT_EQ(ints[i], original_ints[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
Loading…
Reference in a new issue