Bibodui

Сравнение сортировок (кучей, быстрая, выбором)

Jun 2nd, 2023
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 9.03 KB | None | 0 0
  1. //Source.cpp
  2. #include <iostream>
  3. #include <Windows.h>
  4. #include <fstream>
  5. #include <ctime>
  6. #include <algorithm>
  7. #include <string>
  8. #include "Source1.h"
  9. #include "Sort.h"
  10.  
  11. using namespace std;
  12.  
  13. int compare1 = 0;
  14. int compare2 = 0;
  15. int compare3 = 0;
  16. int replace1 = 0;
  17. int replace2 = 0;
  18. int replace3 = 0;
  19.  
  20. int main()
  21. {
  22.     SetConsoleOutputCP(1251);
  23.     SetConsoleCP(1251);
  24.  
  25.     int q;
  26.  
  27.     do
  28.     {
  29.         string Sorted_Data = "Sorted_Data.txt";
  30.         string Reverse_Sorted_Data = "Reverse_Sorted_Data.txt";
  31.         string Half_Sorted_Data = "Half_Sorted_Data.txt";
  32.  
  33.         int size;
  34.         cout << "Введите размер массива:" << endl;
  35.         cin >> size;
  36.  
  37.         create_data(Sorted_Data, size);
  38.         create_data(Reverse_Sorted_Data, size);
  39.         create_data(Half_Sorted_Data, size);
  40.  
  41.         int* selection_arr = new int[size];
  42.         int* quick_arr = new int[size];
  43.         int* heap_sort_arr = new int[size];
  44.  
  45.         ///////////////////////////////////////////////////////////////////////////
  46.  
  47.         fill_array(selection_arr, Sorted_Data, size);
  48.         fill_array(quick_arr, Sorted_Data, size);
  49.         fill_array(heap_sort_arr, Sorted_Data, size);
  50.  
  51.         Sort tmp(selection_arr);
  52.         Sort tmp_heap(heap_sort_arr);
  53.         cout << "\nРабота сортировок на отсортированных данных:" << endl;
  54.         cout << "Сортировка выбором (секунд): " << tmp.selection_sort(size) << endl;
  55.         cout << "Быстрая сортировка (секунд): " << tmp.quick_sort_count(quick_arr, 0, size - 1) << endl;
  56.         cout << "Сортировка кучей (секунд): " << tmp_heap.heap_sort(heap_sort_arr, size) << endl;
  57.         cout << "В сортировке выбором сравнений: " << compare1 << ", перестановок: " << replace1 << endl;
  58.         cout << "В быстрой сортировке сравнений: " << compare2 << ", перестановок: " << replace2 << endl;
  59.         cout << "В сортировке кучей сравнений: " << compare3 << ", перестановок: " << replace3 << endl;
  60.  
  61.         compare1 = compare2 = compare3 = replace1 = replace2 =  replace3 = 0;
  62.  
  63.         ///////////////////////////////////////////////////////////////////////////
  64.  
  65.         fill_array(selection_arr, Reverse_Sorted_Data, size);
  66.         fill_array(quick_arr, Reverse_Sorted_Data, size);
  67.         fill_array(heap_sort_arr, Reverse_Sorted_Data, size);
  68.  
  69.         Sort tmp2(selection_arr);
  70.         Sort tmp_heap2(heap_sort_arr);
  71.         cout << "\nРабота сортировок на отсортированных в обратном порядке данных:" << endl;
  72.         cout << "Сортировка выбором (секунд): " << tmp2.selection_sort(size) << endl;
  73.         cout << "Быстрая сортировка (секунд): " << tmp2.quick_sort_count(quick_arr, 0, size - 1) << endl;
  74.         cout << "Сортировка кучей (секунд): " << tmp_heap2.heap_sort(heap_sort_arr, size) << endl;
  75.         cout << "В сортировке выбором сравнений: " << compare1 << ", перестановок: " << replace1 << endl;
  76.         cout << "В быстрой сортировке сравнений: " << compare2 << ", перестановок: " << replace2 << endl;
  77.         cout << "В сортировке кучей сравнений: " << compare3 << ", перестановок: " << replace3 << endl;
  78.  
  79.         compare1 = compare2 = compare3 = replace1 = replace2 = replace3 = 0;
  80.  
  81.         ///////////////////////////////////////////////////////////////////////////
  82.  
  83.         fill_array(selection_arr, Half_Sorted_Data, size);
  84.         fill_array(quick_arr, Half_Sorted_Data, size);
  85.         fill_array(heap_sort_arr, Half_Sorted_Data, size);
  86.  
  87.         Sort tmp3(selection_arr);
  88.         Sort tmp_heap3(heap_sort_arr);
  89.         cout << "\nРабота сортировок на частично отсортированных данных:" << endl;
  90.         cout << "Сортировка выбором (секунд): " << tmp3.selection_sort(size) << endl;
  91.         cout << "Быстрая сортировка (секунд): " << tmp3.quick_sort_count(quick_arr, 0, size - 1) << endl;
  92.         cout << "Сортировка кучей (секунд): " << tmp_heap3.heap_sort(heap_sort_arr, size) << endl;
  93.         cout << "В сортировке выбором сравнений: " << compare1 << ", перестановок: " << replace1 << endl;
  94.         cout << "В быстрой сортировке сравнений: " << compare2 << ", перестановок: " << replace2 << endl;
  95.         cout << "В сортировке кучей сравнений: " << compare3 << ", перестановок: " << replace3 << endl;
  96.  
  97.         compare1 = compare2 = compare3 = replace1 = replace2 = replace3 = 0;
  98.  
  99.         cout << "\n0. Выход" << endl;
  100.         cin >> q;
  101.     } while (q != 0);
  102. }
  103.  
  104. //Source1.h
  105. #pragma once
  106. #include <iostream>
  107. #include <Windows.h>
  108. #include <fstream>
  109. #include <ctime>
  110. #include <algorithm>
  111. #include <string>
  112.  
  113. using namespace std;
  114.  
  115. void create_data(string, int);
  116. void fill_array(int*, string, int);
  117. void output_array(int*, int);
  118. bool comp(int, int);//компаратор, для функции sort для сортировки в обратном порядке
  119.  
  120. //Source1.cpp
  121. #include "Source1.h"
  122.  
  123. void create_data(string s1, int size)
  124. {
  125.     int* arr = new int[size];
  126.  
  127.     srand(static_cast<int>(time(0)));
  128.  
  129.     for (int i = 0; i < size; i++)
  130.         arr[i] = rand() % size;
  131.  
  132.     if (s1 == "Sorted_Data.txt")
  133.         sort(arr, arr + size);
  134.     else if (s1 == "Reverse_Sorted_Data.txt")
  135.         sort(arr, arr + size, comp);
  136.     else if (s1 == "Half_Sorted_Data.txt")
  137.         sort(arr, arr + size / 2);
  138.  
  139.     fstream file_1;
  140.     file_1.open(s1, ios::out);
  141.  
  142.     for (int i = 0; i < size; i++)
  143.     {
  144.         file_1 << arr[i];
  145.         file_1 << ' ';
  146.     }
  147.     file_1.close();
  148.  
  149.  
  150. }
  151. void output_array(int* arr, int size)
  152. {
  153.     for (int i = 0; i < size; i++)
  154.     {
  155.         cout << arr[i] << '\t';
  156.         if (!((i + 1) % 15))
  157.             cout << endl;
  158.     }
  159.     cout << endl;
  160. }
  161. void fill_array(int* arr, string s1, int size)
  162. {
  163.     fstream file_1;
  164.  
  165.     file_1.open(s1, ios::in);
  166.     for (int i = 0; i < size; i++)
  167.         file_1 >> arr[i];
  168.  
  169.     file_1.close();
  170. }
  171. bool comp(int first, int second)
  172. {
  173.     return first > second;
  174. }
  175.  
  176. //Sort.h
  177. #pragma once
  178. #include <iostream>
  179. #include <ctime>
  180.  
  181. using namespace std;
  182. class Sort
  183. {
  184. private:
  185.     int* arr;
  186.     void quick_sort(int*, int, int);
  187.     void heapify(int*, int, int);
  188. public:
  189.     Sort(int*);
  190.     double selection_sort(int);
  191.     double quick_sort_count(int*, int, int);
  192.     double heap_sort(int*, int);
  193. };
  194.  
  195. //Sort.cpp
  196. #include "Sort.h"
  197.  
  198. extern int compare1;
  199. extern int compare2;
  200. extern int compare3;
  201. extern int replace1;
  202. extern int replace2;
  203. extern int replace3;
  204.  
  205. void Sort::quick_sort(int* arr, int first, int last)
  206. {
  207.     int mid;
  208.     int f = first, l = last;
  209.     mid = arr[(f + l) / 2]; //вычисление опорного элемента
  210.     do
  211.     {
  212.         while (arr[f] < mid)
  213.         {
  214.             f++;
  215.             compare2++;
  216.         }
  217.         while (arr[l] > mid)
  218.         {
  219.             l--;
  220.             compare2++;
  221.         }
  222.         compare2 += 2;
  223.         if (f <= l) //перестановка элементов
  224.         {
  225.             swap(arr[f], arr[l]);
  226.             replace2++;
  227.             f++;
  228.             l--;
  229.         }
  230.     } while (f < l);
  231.     if (first < l) quick_sort(arr, first, l);
  232.     if (f < last) quick_sort(arr, f, last);
  233. }
  234. Sort::Sort(int* arr2)
  235. {
  236.     arr = arr2;
  237. }
  238. double Sort::selection_sort(int size)
  239. {
  240.     double start = clock();
  241.     for (int i = 0; i < size - 1; i++)
  242.     {
  243.         int min = i;
  244.         for (int j = i + 1; j < size; j++)
  245.         {
  246.             compare1++;
  247.             if (arr[j] < arr[min])
  248.                 min = j;
  249.         }
  250.  
  251.         if (min != i)
  252.         {
  253.             swap(arr[i], arr[min]);
  254.             replace1++;
  255.         }
  256.     }
  257.     double stop = clock();
  258.     return ((stop - start) / CLK_TCK);
  259. }
  260. double Sort::quick_sort_count(int* arr, int first, int last)
  261. {
  262.     double start = clock();
  263.     quick_sort(arr, first, last);
  264.     double stop = clock();
  265.     return ((stop - start) / CLK_TCK);
  266. }
  267. void Sort::heapify(int* arr, int n, int i)
  268. {
  269.     int largest = i;      // Инициализируем наибольший элемент как корень
  270.     int left = 2 * i + 1; // Левый потомок
  271.     int right = 2 * i + 2; // Правый потомок
  272.  
  273.     compare3++;
  274.     if (left < n && arr[left] > arr[largest]) // Если левый потомок больше корня
  275.         largest = left;
  276.  
  277.     compare3++;
  278.     if (right < n && arr[right] > arr[largest]) // Если правый потомок больше корня
  279.         largest = right;
  280.  
  281.     if (largest != i) // Если самый большой элемент оказался не корень
  282.     {
  283.         swap(arr[i], arr[largest]);
  284.         replace3++;
  285.         heapify(arr, n, largest); // Проверяем, удовлетворяет ли поддерево свойству кучи
  286.     }
  287. }
  288. double Sort::heap_sort(int* arr, int n)
  289. {
  290.     double start = clock();
  291.    
  292.     for (int i = n / 2 - 1; i >= 0; i--) // Построение кучи (перегруппировка массива)
  293.         heapify(arr, n, i);
  294.  
  295.     for (int i = n - 1; i >= 0; i--) // Извлекаем элементы из кучи по одному и устанавливаем их в конец
  296.     {
  297.         swap(arr[0], arr[i]);
  298.         replace3++;
  299.         heapify(arr, i, 0); // Вызываем функцию heapify на уменьшенной куче
  300.     }
  301.  
  302.     double stop = clock();
  303.     return ((stop - start) / CLK_TCK);
  304. }
Add Comment
Please, Sign In to add comment