Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <algorithm>
- #include <random>
- #include <ctime>
- const int SIZE{ 10 };
- void merge(std::vector<int>& array, int left, int middle, int right) {
- int numElementsLeft{ middle - left + 1 };
- int numElementsRight{ right - middle };
- std::vector<int> leftArray(numElementsLeft);
- std::vector<int> rightArray(numElementsRight);
- for (int index{}; index < numElementsLeft; ++index) {
- leftArray[index] = array[left + index];
- }
- for (int index{}; index < numElementsRight; ++index) {
- rightArray[index] = array[middle + 1 + index];
- }
- int i{}, j{}, k{ left };
- while (i < numElementsLeft && j < numElementsRight) {
- if (leftArray[i] <= rightArray[j]) {
- array[k] = leftArray[i];
- ++i;
- }
- else {
- array[k] = rightArray[j];
- ++j;
- }
- ++k;
- }
- while (i < numElementsLeft) {
- array[k] = leftArray[i];
- ++i;
- ++k;
- }
- while (j < numElementsRight) {
- array[k] = rightArray[j];
- ++j;
- ++k;
- }
- }
- void iterativeMergeSort(std::vector<int>& array) {
- int numElements{ static_cast<int>(array.size()) };
- for (int currentSize{ 1 }; currentSize <= numElements - 1; currentSize *= 2) {
- for (int leftStart{}; leftStart < numElements - 1; leftStart += 2 * currentSize) {
- int middle{ std::min(leftStart + currentSize - 1, numElements - 1) };
- int rightEnd{ std::min(leftStart + 2 * currentSize - 1, numElements - 1) };
- merge(array, leftStart, middle, rightEnd);
- }
- }
- }
- void handleFillArray() {
- std::vector<int> array(SIZE);
- std::cout << "Original array (size is " << SIZE << "): ";
- int temporal;
- for (int& num : array) {
- std::cin >> temporal;
- num = temporal;
- }
- iterativeMergeSort(array);
- std::cout << "Sorted array: ";
- for (int num : array) {
- std::cout << num << " ";
- }
- }
- void randomAutoFillTest() {
- std::vector<int> array;
- std::random_device rd;
- std::mt19937 gen(time(0));
- std::uniform_int_distribution<int> dis(-100, 100);
- for (int index = 0; index < SIZE; ++index) {
- array.push_back(dis(gen));
- }
- std::cout << "Original array: ";
- for (int num : array) {
- std::cout << num << " ";
- }
- iterativeMergeSort(array);
- std::cout << "\nSorted array: ";
- for (int num : array) {
- std::cout << num << " ";
- }
- }
- void testModeSelection() {
- std::cout << "Select the test mode: \n1. Manual input \n2. Auto input of random values \nmodeSelectionValue is ";
- int modeSelectionValue;
- std::cin >> modeSelectionValue;
- if (modeSelectionValue == 1) {
- handleFillArray();
- } else if (modeSelectionValue == 2) {
- randomAutoFillTest();
- } else {
- std::cout << "Incorrect test mode value\n";
- }
- }
- int main() {
- testModeSelection();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement