mirror of
https://github.com/RGBCube/serenity
synced 2025-07-27 02:27:43 +00:00
AK: Introduce cutoff to insertion sort for Quicksort
Implement insertion sort in AK. The cutoff value 7 is a magic number here, values [5, 15] should work well. Main idea of the cutoff is to reduce recursion performed by quicksort to speed up sorting of small partitions.
This commit is contained in:
parent
bbb256e8b5
commit
22f472249d
4 changed files with 119 additions and 0 deletions
|
@ -1,11 +1,13 @@
|
|||
/*
|
||||
* Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
|
||||
* Copyright (c) 2022, Marc Luqué <marc.luque@outlook.com>
|
||||
*
|
||||
* SPDX-License-Identifier: BSD-2-Clause
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <AK/InsertionSort.h>
|
||||
#include <AK/StdLibExtras.h>
|
||||
|
||||
namespace AK {
|
||||
|
@ -14,10 +16,24 @@ namespace AK {
|
|||
* pivot quick_sort below. The other quick_sort below should only be used when
|
||||
* you are stuck with simple iterators to a container and you don't have access
|
||||
* to the container itself.
|
||||
*
|
||||
* We use a cutoff to insertion sort for partitions of size 7 or smaller.
|
||||
* The idea is to avoid recursion for small partitions.
|
||||
* The value 7 here is a magic number. According to princeton's CS algorithm class
|
||||
* a value between 5 and 15 should work well in most situations:
|
||||
* https://algs4.cs.princeton.edu/23quicksort/
|
||||
*/
|
||||
|
||||
static constexpr int INSERTION_SORT_CUTOFF = 7;
|
||||
|
||||
template<typename Collection, typename LessThan>
|
||||
void dual_pivot_quick_sort(Collection& col, int start, int end, LessThan less_than)
|
||||
{
|
||||
if ((end + 1) - start <= INSERTION_SORT_CUTOFF) {
|
||||
AK::insertion_sort(col, start, end, less_than);
|
||||
return;
|
||||
}
|
||||
|
||||
while (start < end) {
|
||||
int size = end - start + 1;
|
||||
if (size > 3) {
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue