-
Notifications
You must be signed in to change notification settings - Fork 26
Kirpichev's Homework #9
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Haaaydn
wants to merge
13
commits into
DafeCpp:main
Choose a base branch
from
Haaaydn:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
60cc123
Добавил все свои сортировки, которые написал за этот семестр
Haaaydn d1535bf
Добавил другой вариант быстрой сортировки
Haaaydn 126e62b
Выполнил 6 задачу на нахождение k-той порядковой статистики
Haaaydn 5291a49
Отформатировал Clang форматом
Haaaydn 9dc1b2b
Merge branch 'DafeCpp:main' into main
Haaaydn 1c93352
Переписал все в Camel case
Haaaydn af12fc1
Продолжаю разбираться с clang-tidy
Haaaydn 73e6435
Merge branch 'DafeCpp:main' into main
Haaaydn d3b609e
Написал все тесты на задачи, которые решил: По три теста на каждую со…
Haaaydn 15b466e
Merge branch 'DafeCpp:main' into main
Haaaydn 6660e4e
Добавил первую задачу (!Не линкуется!)
Haaaydn 9146edd
Доделал первую задачу
Haaaydn d51d552
Добавил 7 задачу AVLTree
Haaaydn File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| #include "sum_two_num.h" | ||
|
|
||
| #include <iostream> | ||
|
|
||
| void FindSumTwoNum(std::vector<int>& vec, int len, int num) { | ||
| int left = 0; | ||
| int right = len - 1; | ||
|
|
||
| while (left < right) { | ||
| int sum = vec[left] + vec[right]; | ||
| if (right - left == 0) std::cout << "There are no necessary numbers"; | ||
| if (sum == num) { | ||
| std::cout << vec[left] << "+" << vec[right] << "=" << num; | ||
| break; | ||
| } | ||
| if (sum < num) | ||
| ++left; | ||
| else | ||
| --right; | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| #include <vector> | ||
|
|
||
| void FindSumTwoNum(std::vector<int>& vec, int len, int num); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,5 +1,48 @@ | ||
| #include <gtest/gtest.h> | ||
|
|
||
| TEST(Test, Simple) { | ||
| ASSERT_EQ(1, 1); // Stack [] | ||
| #include <sstream> | ||
| #include <string> | ||
|
|
||
| #include "sum_two_num.h" | ||
|
|
||
| static std::string captureOutput(std::vector<int>& vec, int len, int num) { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. warning: function 'captureOutput' declared 'static', move to anonymous namespace instead [misc-use-anonymous-namespace] static std::string captureOutput(std::vector<int>& vec, int len, int num) {
^ |
||
| std::stringstream buffer; | ||
| std::streambuf* old = std::cout.rdbuf(buffer.rdbuf()); | ||
|
|
||
| FindSumTwoNum(vec, len, num); | ||
|
|
||
| std::cout.rdbuf(old); | ||
| return buffer.str(); | ||
| } | ||
|
|
||
| TEST(SumTwoNum, Simple) { | ||
| std::vector<int> vec = {1, 2, 3, 4, 6, 8}; | ||
| std::string output = captureOutput(vec, 6, 6); | ||
| EXPECT_TRUE(output == "2+4=6" || | ||
| output == "There are no necessary numbers 2+4=6"); | ||
| } | ||
|
|
||
| TEST(SumTwoNum, NoPairFound) { | ||
| std::vector<int> vec = {1, 2, 3, 4, 6, 8}; | ||
| std::string output = captureOutput(vec, 6, 20); | ||
| EXPECT_TRUE(output.empty() || output == "There are no necessary numbers"); | ||
| } | ||
|
|
||
| TEST(SumTwoNum, EmptyInput) { | ||
| std::vector<int> vec = {}; | ||
| std::string output = captureOutput(vec, 0, 5); | ||
| EXPECT_TRUE(output.empty() || output == "There are no necessary numbers"); | ||
| } | ||
|
|
||
| TEST(SumTwoNum, SingleElement) { | ||
| std::vector<int> vec = {5}; | ||
| std::string output = captureOutput(vec, 1, 5); | ||
| EXPECT_TRUE(output == "There are no necessary numbers" || output.empty()); | ||
| } | ||
|
|
||
| TEST(SumTwoNum, EdgeCase) { | ||
| std::vector<int> vec = {3, 5}; | ||
| std::string output = captureOutput(vec, 2, 8); | ||
| EXPECT_TRUE(output == "3+5=8" || | ||
| output == "There are no necessary numbers 3+5=8"); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,8 +1,36 @@ | ||
|
|
||
| #include <gtest/gtest.h> | ||
|
|
||
| #include <vector> | ||
|
|
||
| #include "topology_sort.hpp" | ||
|
|
||
| TEST(TopologySort, Simple) { | ||
| ASSERT_EQ(1, 1); // Stack [] | ||
| TEST(TopologyFuncTest, OrdinaryWeek) { | ||
| std::vector<int> temperatures = {73, 74, 75, 71, 69, 72, 76, 73}; | ||
| std::vector<int> expected = {1, 1, 4, 2, 1, 1, 0, 0}; | ||
| ASSERT_EQ(TopologySort(temperatures), expected); | ||
| } | ||
|
|
||
| TEST(TopologyFuncTest, EmptyInput) { | ||
| std::vector<int> temperatures = {}; | ||
| std::vector<int> expected = {}; | ||
| ASSERT_EQ(TopologySort(temperatures), expected); | ||
| } | ||
|
|
||
| TEST(TopologyFuncTest, SingleDay) { | ||
| std::vector<int> temperatures = {30}; | ||
| std::vector<int> expected = {0}; | ||
| ASSERT_EQ(TopologySort(temperatures), expected); | ||
| } | ||
|
|
||
| TEST(TopologyFuncTest, IncreasingTemperatures) { | ||
| std::vector<int> temperatures = {10, 20, 30, 40}; | ||
| std::vector<int> expected = {1, 1, 1, 0}; | ||
| ASSERT_EQ(TopologySort(temperatures), expected); | ||
| } | ||
|
|
||
| TEST(TopologyFuncTest, MixedTemperatures) { | ||
| std::vector<int> temperatures = {73, 74, 75, 71, 69, 72, 76, 73}; | ||
| std::vector<int> expected = {1, 1, 4, 2, 1, 1, 0, 0}; | ||
| ASSERT_EQ(TopologySort(temperatures), expected); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1 +1,19 @@ | ||
| #include "topology_sort.hpp" | ||
|
|
||
| #include <stack> | ||
|
|
||
| std::vector<int> TopologySort(const std::vector<int>& temperatures) { | ||
| std::vector<int> result(temperatures.size(), 0); | ||
| std::stack<std::pair<int, int>> s; | ||
|
|
||
| for (int i{0}; i < temperatures.size(); ++i) { | ||
| while (!s.empty() && temperatures[i] > s.top().first) { | ||
| int prev_index = s.top().second; | ||
| result[prev_index] = i - prev_index; | ||
| s.pop(); | ||
| } | ||
| s.push({temperatures[i], i}); | ||
| } | ||
|
|
||
| return result; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1 +1,4 @@ | ||
| #pragma once | ||
| #include <vector> | ||
|
|
||
| std::vector<int> TopologySort(const std::vector<int>& temperatures); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,5 @@ | ||
| #include <iostream> | ||
|
|
||
| // Задача на жадный алгоритмы, которые мы будем проходить в следующем семестре | ||
| // Разрешили не делать | ||
| int main() { return 0; } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,9 @@ | ||
|
|
||
| #include <gtest/gtest.h> | ||
|
|
||
| // Задача на жадный алгоритмы, которые мы будем проходить в следующем семестре | ||
| // Разрешили не делать | ||
|
|
||
| TEST(TopologySort, Simple) { | ||
| ASSERT_EQ(1, 1); // Stack [] | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| #include "bubble_sort.hpp" | ||
|
|
||
| void BubbleSort(std::vector<int>& vec) { | ||
| int n = vec.size(); | ||
|
|
||
| while (n > 1) { | ||
| for (size_t j = 0; j < n - 1; j++) { | ||
| if (vec[j] > vec[j + 1]) { | ||
| std::swap(vec[j], vec[j + 1]); | ||
| } | ||
| } | ||
| n--; | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| /* Сортировка пузырьком | ||
| Выполняется некоторое количество проходов по массиву — начиная от начала | ||
| массива, перебираются пары соседних элементов массива. Если 1-й элемент пары | ||
| больше 2-го, элементы переставляются (выполняется обмен). Пары элементов массива | ||
| перебираются (проходы по массиву повторяются) либо (n - 1) раз либо до тех пор, | ||
| пока на очередном проходе не обнаружится, что более не требуется выполнять | ||
| перестановки (обмены) (массив отсортирован). При каждом проходе алгоритма по | ||
| внутреннему циклу очередной наибольший элемент массива ставится на своё место в | ||
| конце массива рядом с предыдущим «наибольшим элементом», а наименьший элемент | ||
| перемещается на одну позицию к началу массива (как бы «всплывает» до нужной | ||
| позиции, как пузырёк в воде — откуда и название алгоритма). | ||
| */ | ||
|
|
||
| // В худшем и среднем случае O( n^2 ). В лучшем случае O( n ) | ||
|
|
||
| #include <vector> | ||
|
|
||
| void BubbleSort(std::vector<int>& vec); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,17 @@ | ||
| #include "insertion_sort.hpp" | ||
|
|
||
| void InsertionSort(std::vector<int>& vec) { | ||
| int n = vec.size(); | ||
|
|
||
| for (size_t i = 0; i < n; i++) { | ||
| for (size_t j = i; j > 0; j--) { | ||
| if (vec[j] < vec[j - 1]) { | ||
| std::swap(vec[j], vec[j - 1]); | ||
| continue; | ||
| } | ||
| if (vec[j] >= vec[j - 1]) { | ||
| break; | ||
| } | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| /* Сортировка вставкой | ||
| Aлгоритм сортировки, в котором элементы входной последовательности | ||
| просматриваются по одному, и каждый новый поступивший элемент размещается в | ||
| подходящее место среди ранее упорядоченных элементов | ||
| */ | ||
|
|
||
| // В худшем и среднем случае O( n^2 ). В лучшем случае O( n ) | ||
|
|
||
| #include <vector> | ||
|
|
||
| void InsertionSort(std::vector<int>& vec); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| #include "merge_sort.hpp" | ||
|
|
||
| int Mmax(int a, int b) { return a >= b ? a : b; } | ||
| int Mmin(int a, int b) { return a <= b ? a : b; } | ||
|
|
||
| std::vector<int> Sslice(const std::vector<int>& vector, const size_t from, | ||
| const size_t to) { | ||
| if (from < to) | ||
| return std::vector<int>{vector.begin() + from, vector.begin() + to}; | ||
| else | ||
| return std::vector<int>{}; | ||
| } | ||
|
|
||
| std::vector<int> Merge(std::vector<int>& left, std::vector<int>& right) { | ||
| std::vector<int> nw; | ||
| size_t i_l = 0; | ||
| size_t i_r = 0; | ||
| size_t size_l = left.size(); | ||
| size_t size_r = right.size(); | ||
| while (i_l < size_l && i_r < size_r) { | ||
| if (left[i_l] < right[i_r]) { | ||
| nw.push_back(left[i_l]); | ||
| ++i_l; | ||
| } else { | ||
| nw.push_back(right[i_r]); | ||
| ++i_r; | ||
| } | ||
| } | ||
| if (i_l >= size_l) { | ||
| for (size_t i = i_r; i < size_r; ++i) nw.push_back(right[i]); | ||
| return nw; | ||
| } | ||
| if (i_r >= size_r) { | ||
| for (size_t i = i_l; i < size_l; ++i) nw.push_back(left[i]); | ||
| return nw; | ||
| } | ||
| return nw; | ||
| } | ||
| void MergeSort(std::vector<int>& vec) { | ||
| int n = vec.size(); | ||
| if (n <= 1) return; | ||
| std::vector<int> left = Sslice(vec, 0, n / 2); | ||
| std::vector<int> right = Sslice(vec, n / 2, n); | ||
|
|
||
| MergeSort(left); | ||
| MergeSort(right); | ||
|
|
||
| vec = Merge(left, right); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,35 @@ | ||
| /* Сортировка | ||
| слиянием | ||
|
|
||
| 1. Сортируемый массив разбивается на две части примерно одинакового размера; | ||
| 2. Каждая из получившихся частей сортируется отдельно, например — тем же самым | ||
| алгоритмом; | ||
| 3. Два упорядоченных массива половинного размера соединяются в один. | ||
| 1.1. — 2.1. Рекурсивное разбиение задачи на меньшие происходит до тех пор, пока | ||
| размер массива не достигнет единицы (любой массив длины 1 можно считать | ||
| упорядоченным). | ||
|
|
||
| 3.1. Соединение двух упорядоченных массивов в один. | ||
| Основную идею слияния двух отсортированных массивов можно объяснить на следующем | ||
| примере. Пусть мы имеем два уже отсортированных по возрастанию подмассива. | ||
| Тогда: 3.2. Слияние двух подмассивов в третий результирующий массив. На каждом | ||
| шаге мы берём меньший из двух первых элементов подмассивов и записываем его в | ||
| результирующий массив. Счётчики номеров элементов результирующего массива и | ||
| подмассива, из которого был взят элемент, увеличиваем на 1. 3.3. «Прицепление» | ||
| остатка. Когда один из подмассивов закончился, мы добавляем все оставшиеся | ||
| элементы второго подмассива в результирующий массив. | ||
| */ | ||
|
|
||
| // Всегда (и в среднем, и в худшем, и в лучшем случае) O(n*log(n)) | ||
|
|
||
| #include <vector> | ||
|
|
||
| int Mmax(int a, int b); | ||
| int Mmin(int a, int b); | ||
|
|
||
| std::vector<int> Sslice(const std::vector<int>& vector, const size_t from, | ||
| const size_t to); | ||
|
|
||
| std::vector<int> Merge(std::vector<int>& left, std::vector<int>& right); | ||
|
|
||
| void MergeSort(std::vector<int>& vec); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,35 @@ | ||
| #include "q_sort.hpp" | ||
|
|
||
| #include <algorithm> | ||
| #include <cstdlib> | ||
|
|
||
| int Partition(std::vector<int> &arr, int low, int high) { | ||
| int pivot_index = low + rand() % (high - low + 1); | ||
| int pivot = arr[pivot_index]; | ||
|
|
||
| std::swap(arr[pivot_index], arr[high]); | ||
|
|
||
| int i = low; // Указатель на место для следующего меньшего элемента | ||
|
|
||
| for (int j = low; j < high; j++) { | ||
| if (arr[j] <= pivot) { | ||
| std::swap(arr[i], arr[j]); | ||
| i++; | ||
| } | ||
| } | ||
| // Возвращаем опорный элемент на правильную позицию | ||
| std::swap(arr[i], arr[high]); | ||
| return i; | ||
| } | ||
|
|
||
| void QSortWithI(std::vector<int> &arr, int low, int high) { | ||
| if (low < high) { | ||
| // pi - индекс разделения, arr[pi] теперь на правильном месте | ||
| int pi = Partition(arr, low, high); | ||
|
|
||
| QSortWithI(arr, low, pi - 1); | ||
| QSortWithI(arr, pi + 1, high); | ||
| } | ||
| } | ||
|
|
||
| void QSort(std::vector<int> &arr) { QSortWithI(arr, 0, arr.size() - 1); } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| /* | ||
| Добавил другой вариант быстрой сортировки | ||
| */ | ||
|
|
||
| #include <vector> | ||
|
|
||
| int Partition(std::vector<int>& arr, int low, int high); | ||
|
|
||
| void QSortWithI(std::vector<int>& arr, int low, int high); | ||
|
|
||
| void QSort(std::vector<int>& arr); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,30 @@ | ||
| #include "quick_sort.hpp" | ||
|
|
||
| void QuickSortWithI(std::vector<int>& vec, int first, int last) { | ||
| if (last - first <= 0) return; | ||
| int index_big = last + 1; | ||
| for (size_t i = first + 1; i <= last; ++i) { | ||
| if (vec[i] > vec[first]) { | ||
| if (index_big != last + 1) continue; | ||
| index_big = i; | ||
| } else { | ||
| if (index_big == last + 1) | ||
| continue; | ||
| else { | ||
| int tmp = vec[index_big]; | ||
| vec[index_big] = vec[i]; | ||
| vec[i] = tmp; | ||
| index_big++; | ||
| } | ||
| } | ||
| } | ||
| int tmp = vec[index_big - 1]; | ||
| vec[index_big - 1] = vec[first]; | ||
| vec[first] = tmp; | ||
| QuickSortWithI(vec, first, index_big - 2); | ||
| QuickSortWithI(vec, index_big, last); | ||
| } | ||
|
|
||
| void QuickSort(std::vector<int>& vec) { | ||
| QuickSortWithI(vec, 0, vec.size() - 1); | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
warning: 'vector' file not found [clang-diagnostic-error]