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 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
|
#include <iostream>
#include <chrono>
#include <random>
const int Size = 100000;
void mergeSort(int array[], int left, int right);
void printArray(int array[], int size);
void mergesortX(int *a, int n);
class Clock
{
using Clk = std::chrono::steady_clock;
Clk clk;
Clk::time_point mStart, mEnd;
public:
Clock() { mStart = clk.now(); }
Clk::time_point get_start() const { return mStart; }
Clk::time_point get_end() const { return mEnd; }
void start() { mStart = clk.now(); }
void end() { mEnd = clk.now(); }
void end_ms() { end(); print_ms(); }
void end_us() { end(); print_us(); }
Clk::duration dur() const { return mEnd - mStart; }
template<typename D>
auto ticks() const
{ return std::chrono::duration_cast<D>(dur()).count(); }
void print_ms() const
{ std::cout << ticks<std::chrono::milliseconds>() << "ms\n"; }
void print_us() const
{ std::cout << ticks<std::chrono::microseconds>() << "us\n"; }
};
int main()
{
std::default_random_engine rnd(std::random_device{}());
std::uniform_int_distribution<> dist(0, Size * 10);
auto a {new int[Size]};
for (int i = 0; i < Size; ++i) a[i] = dist(rnd);
Clock clk;
// mergeSort(a, 0, Size - 1);
mergesortX(a, Size);
clk.end_us();
if (Size <= 100) printArray(a, Size);
}
void merge(int array[], int start, int middle, int end)
{
int start2 = middle + 1;
if (array[middle] <= array[start2])
return;
while (start <= middle && start2 <= end) {
if (array[start] > array[start2]) {
int value = array[start2];
for (int i = start2; i != start; --i)
array[i] = array[i - 1];
array[start] = value;
++middle;
++start2;
}
++start;
}
}
void mergeSort(int array[], int left, int right) {
if (left < right) {
int m = left + (right - left) / 2;
mergeSort(array, left, m);
mergeSort(array, m + 1, right);
merge(array, left, m, right);
}
}
void printArray(int array[], int size) {
for (int i = 0; i < size; ++i) std::cout << ' ' << array[i];
std::cout << '\n';
}
void mergeX(int *a, int size, int istart, int n, int *buf) {
int i = istart, j = istart + size, k = istart;
const int iend = j, jend = j + size < n ? j + size : n;
while (i < iend && j < jend)
buf[k++] = a[i] <= a[j] ? a[i++] : a[j++];
while (i < iend) buf[k++] = a[i++];
while (j < jend) buf[k++] = a[j++];
for (int x = istart; x < jend; ++x) a[x] = buf[x];
}
void mergesortX(int *a, int n) {
auto buf = new int[n];
for (int size = 1; size < n; size *= 2)
for (int i = 0; i + size <= n; i += size * 2)
mergeX(a, size, i, n, buf);
delete[] buf;
}
|