summaryrefslogtreecommitdiff
path: root/AK/InsertionSort.h
diff options
context:
space:
mode:
authorMarc Luqué <marc.luque@outlook.com>2022-03-25 17:06:11 +0100
committerLinus Groh <mail@linusgroh.de>2022-12-12 15:03:57 +0000
commit22f472249d25a7d3885f281932dfb89619089577 (patch)
tree4da19f66951722806a100be5710703ba49e4d06a /AK/InsertionSort.h
parentbbb256e8b50e38dd8b68f39827de5bad8c1d4a6e (diff)
downloadserenity-22f472249d25a7d3885f281932dfb89619089577.zip
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.
Diffstat (limited to 'AK/InsertionSort.h')
-rw-r--r--AK/InsertionSort.h45
1 files changed, 45 insertions, 0 deletions
diff --git a/AK/InsertionSort.h b/AK/InsertionSort.h
new file mode 100644
index 0000000000..2ed2e7cab4
--- /dev/null
+++ b/AK/InsertionSort.h
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) 2022, Marc Luqué <marc.luque@outlook.com>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/Concepts.h>
+#include <AK/StdLibExtras.h>
+
+namespace AK {
+
+// Standard Insertion Sort, with `end` inclusive!
+template<typename Collection, typename Comparator, typename T = decltype(declval<Collection>()[declval<int>()])>
+void insertion_sort(Collection& col, ssize_t start, ssize_t end, Comparator comparator)
+requires(Indexable<Collection, T>)
+{
+ for (ssize_t i = start + 1; i <= end; ++i) {
+ for (ssize_t j = i; j > 0 && comparator(col[j], col[j - 1]); --j)
+ swap(col[j], col[j - 1]);
+ }
+}
+
+template<typename Collection, typename Comparator, typename T = decltype(declval<Collection>()[declval<int>()])>
+void insertion_sort(Collection& collection, Comparator comparator)
+requires(Indexable<Collection, T>)
+{
+ if (collection.size() == 0)
+ return;
+ insertion_sort(collection, 0, collection.size() - 1, move(comparator));
+}
+
+template<typename Collection, typename T = decltype(declval<Collection>()[declval<int>()])>
+void insertion_sort(Collection& collection)
+requires(Indexable<Collection, T>)
+{
+ if (collection.size() == 0)
+ return;
+ insertion_sort(collection, 0, collection.size() - 1, [](auto& a, auto& b) { return a < b; });
+}
+
+}
+
+using AK::insertion_sort;