Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

СиАОД_1-4.docx

.pdf
Скачиваний:
7
Добавлен:
23.01.2025
Размер:
1.33 Mб
Скачать

"quickSort"); tread_vector.emplace_back(sort_quickSort);

sortMeter sort_selection( edu::selection_sort<decltype(double_mat->get_iterator())>, *double_mat, "sort_selection");

tread_vector.emplace_back(sort_selection);

sortMeter sort_shell( edu::shell_sort<decltype(double_mat->get_iterator())>, *double_mat, "shell_sort");

tread_vector.emplace_back(sort_shell);

//clang-format on

}

if (integer_mat) {

// clang-format off

sortMeter sort_intro(std::sort<decltype(integer_mat->get_iterator())>, *integer_mat, "introsort libstdc++");

tread_vector.emplace_back(sort_intro);

sortMeter sort_heap_int( edu::heap_sort<decltype(integer_mat->get_iterator())>, *integer_mat, "heap_sort_int");

tread_vector.emplace_back(sort_heap_int);

sortMeter sort_insertion_int( edu::insertion_sort<decltype(integer_mat->get_iterator())>, *integer_mat, "insertion_sort_int");

tread_vector.emplace_back(sort_insertion_int);

sortMeter sort_quickSort_int( edu::quickSort<decltype(integer_mat->get_iterator())>, *integer_mat, "quickSort_int");

tread_vector.emplace_back(sort_quickSort_int);

sortMeter sort_selection_int( edu::selection_sort<decltype(integer_mat->get_iterator())>, *integer_mat, "selection_sort_int");

tread_vector.emplace_back(sort_selection_int);

sortMeter sort_shell_int( edu::shell_sort<decltype(integer_mat->get_iterator())>, *integer_mat, "shell_sort_int");

tread_vector.emplace_back(sort_shell_int);

//clang-format on

}

for (auto &t : tread_vector) { t.join();

}

}

11

Вывод

​ При большем размере матрицы, лучший результат показала встроенная сортировка, затем с небольшим отставанием быстрая сортировка и наихудший, с довольно большим отставанием по времени – сортировка Selection sort. Нормальные результаты показала так же heap sort и shell sort.​

12

Задание 2 Методы поиска

Цель работы

Реализовать заданный метод поиска в соответствии с индивидуальным заданием. Организовать генерацию начального набора случайных данных. Для всех вариантов добавить реализацию добавления, поиска и удаления элементов. Оценить время работы каждого алгоритма поиска и сравнить его со временем работы стандартной функции поиска, используемой в выбранном языке программирования.

Вариант задания 18

Метод поиска: бинарное дерево и метод цепочек.

Ход работы

​ Необходимо реализовать бинарное дерево, в качестве такового будет использовано красно-чёрное дерево, так как может само балансироваться. ​

template <typename T> class rb_tree { public:

// type definitions:

typedef rb_node<T> node_type; typedef rb_iterator<node_type> iterator;

//members node_type *root; unsigned long size;

//Constructors

rb_tree(void) : root(NULL), size(0) {}

template <typename Iterator_> rb_tree(Iterator_ begin, Iterator_ end) { insert(begin, end);

}

// Utility functions

iterator max(void) { return (empty()) ? end() : iterator(root->max()); }

13

iterator min(void) { return (empty()) ? end() : iterator(root->min()); } iterator begin(void) { return min(); }

iterator end(void) { return iterator(); }

bool empty(void) const { return (root == NULL); }

/*Insertion*/

iterator insert(T value) { return iterator(insert(new node_type(value))); }

iterator insert(iterator &current, T &value) { return insert(value); }

template <typename Iterator_> void insert(Iterator_ begin, Iterator_ end) { for (Iterator_ it = begin; it != end; ++it) {

T v = *it; insert(v);

}

}

 

/*​

RED BLACK INSERTION​*/

node_type *insert(node_type *node) { binary_insert(node);

node_type *temp = node; rb_adjust(temp);

return node;

}

// Display tree void print() { if (empty())

std::cout << "No tree initialized"; else

print(root);

}

void inorder_print(node_type *ptr) { if (ptr == NULL)

return;

14

ptr->print(); inorder_print(ptr->left); inorder_print(ptr->right);

}

int height() { return height(root); }

// Binary Search function

node_type *binary_search(int value) { node_type *current = root;

while (current != NULL) {

if (current->value == value) { return current;

}else if (current->value < value) { current = current->right;

}else {

current = current->left;

}

}

return nullptr;

}

protected:

void print(node_type *node) { std::cout << std::endl;

;

if (node == NULL) { std::cout << "____"; return;

}

int h = height();

std::queue<node_type *> currentLevel, nextLevel; currentLevel.push(node);

while (!currentLevel.empty()) {

15

node_type *currNode = currentLevel.front(); currentLevel.pop();

if (currNode != NULL) {

for (int i = (1 << h - 1) * 2; i > 0; i--) std::cout << " ";

std::cout << currNode->value << ":"; if (currNode->color == RED) { std::cout << "R";

} else {

std::cout << "B";

}

nextLevel.push(currNode->left); nextLevel.push(currNode->right);

}

if (currentLevel.empty()) { std::cout << std::endl; h--;

swap(currentLevel, nextLevel);

}

}

}

int height(node_type *node) { if (node == NULL)

return 0;

int heightLeft = height(node->left); int heightRight = height(node->right);

if (heightLeft > heightRight) return heightLeft + 1;

else

return heightRight + 1;

}

// Binary Tree Insertion

node_type *binary_insert(node_type *node) {

16

++size;

// Root insertion case if (empty())

root = node; else {

node_type *current = root; do {

if (current->value < node->value) { if (current->right == NULL) { node->parent = current; current->right = node;

break; } else {

current = current->right;

}

} else if (current->value >= node->value) { if (current->left == NULL) { node->parent = current;

current->left = node; break;

} else {

current = current->left;

}

}

} while (true);

}

return node;

}

// Special functions

void rb_adjust(node_type *node) { // Case 1: Root node

if (node == NULL) return;

if (node->parent == NULL) { node->color = BLACK;

17

return;

}

node_type *p = node->parent; // Case 2: Parent is BLACK

if (p != NULL && p->color == BLACK) return;

//Case 3: Parent and Uncle are RED node_type *u = p->sibling();

if (p->color == RED && (u != NULL && u->color == RED)) { p->color = BLACK;

u->color = BLACK; p->parent->color = RED; rb_adjust(p->parent); return;

}

//Case 4: Parent is Red and Uncle is Black(Or NULL)

//If parent is left son

if (p->is_a_left_son()) {

if (node->is_a_right_son()) { node = p;

left_rotate(p);

}

p->color = BLACK;

if (p->parent != NULL) { p->parent->color = RED; right_rotate(p->parent);

}

return;

}

// If parent is right son

else if (p->is_a_right_son()) {

18

if (node->is_a_left_son()) { node = p;

right_rotate(p);

}

p->color = BLACK;

if (p->parent != NULL) { p->parent->color = RED; left_rotate(p->parent);

}

return;

}

}

// left rotate

void left_rotate(node_type *node) { if (node->right != NULL) {

node_type *right_son = node->right;

if ((node->right = node->right->left) != NULL) node->right->parent = node;

if (node->parent == NULL) root = right_son;

else if (node->is_a_left_son()) node->parent->left = right_son; else

node->parent->right = right_son;

// update right_son's parent: right_son->parent = node->parent;

// the left son of the old right son is this node: node->parent = right_son;

right_son->left = node;

}

}

 

//​

right rotate

void right_rotate(node_type *node) {

19

// check if node has a left son if (node->left != NULL) {

node_type *left_son = node->left;

if ((node->left = node->left->right) != NULL) node->left->parent = node;

if (node->parent == NULL) root = left_son;

else if (node->is_a_left_son())

node->parent->left = left_son;

else

node->parent->right = left_son; left_son->parent = node->parent; node->parent = left_son; left_son->right = node;

}

}

};

#endif

Также сразу приведу исходный код хеш таблицы, которые необходимы для демонстрации работы метода цепочек. ​

#ifndef HASHTABLE_HPP #define HASHTABLE_HPP

#include <functional> #include <utility>

#define DEBUG 1

#ifdef DEBUG #include <iostream> #endif

20