0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

マージソート C++

0
Last updated at Posted at 2021-05-21

C++ によるマージソートの実装
番兵にINT16_MAXを使っているが、適時他を使え。

# include <iostream>
# include <random>
# include <vector>
using namespace std;
# define rep(i, n) for (int i = 0; i < n; i++)

void display(const vector<int> &v) {
    rep(i, v.size()) cout << v[i] << " ";
    cout << endl;
}
// 昇順チェッカー
void ascendingOrderChecker(const vector<int> &v) {
    bool flag = true;
    rep(i, v.size() - 1) flag &= v[i] <= v[i + 1];
    if (flag) {
        cout << "Correctly sorted." << endl;
    } else
        cout << "Not sorted correctly." << endl;
}
void swap(int *a, int *b) {
    int *t = a;
    a = b;
    b = t;
}
void merge(vector<int> &v, int i, int j) {
    int h = (i + j) / 2;

    vector<int> A(h - i + 1);
    vector<int> B(j - (h + 1) + 1);
    for (int s = 0; s < A.size(); s++) A.at(s) = v[i + s];
    for (int t = 0; t < B.size(); t++) B.at(t) = v[h + 1 + t];
    A.push_back(INT16_MAX);
    B.push_back(INT16_MAX);
    int a = 0, b = 0;
    for (int k = i; k <= j; k++) {
        if (A[a] < B[b]) {
            v[k] = A[a];
            a++;
        } else {
            v[k] = B[b];
            b++;
        }
    }
}
void MergeSort(vector<int> &v, int i, int j) {
    if (j - i + 1 == 1) return;
    int h = (i + j) / 2;
    MergeSort(v, i, h);
    MergeSort(v, h + 1, j);
    merge(v, i, j);
}

int main() {
    vector<int> test(100);
    random_device rnd;
    mt19937 mt(rnd());
    uniform_int_distribution<> rand100(-99, 99);
    rep(i, 100) {
        rep(i, 100) test[i] = rand100(mt);
        // ソート前の状態
        ascendingOrderChecker(test);
        MergeSort(test, 0, test.size() - 1);
        // ソート後の状態
        ascendingOrderChecker(test);
        // display(test);
    }
    return 0;
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?