summaryrefslogtreecommitdiff
path: root/AK/InsertionSort.h
blob: 2ed2e7cab423899d1442a8219ec88a5519c0491d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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;