Website Summary Files Commits Branches @commit @diff @stats
path: root / Practicum / pract03 / merge.cpp
diff options
context:
space:
mode:
Commitdbd2a89e755ac4941f3afbf3bf78ecb810d1bf55 (patch)
Author
 Desislava Shunina <115353472+desiish@users.noreply.github.com>
2024-10-22 17:37:35 +0300
Committer
 GitHub <noreply@github.com>
2024-10-22 17:37:35 +0300
Files7d2368adb4e0de27d259d2e4ab6d60a897de37be /Practicum/pract03/merge.cpp
Data-structures-and-algorithms-dbd2a89e755ac4941f3afbf3bf78ecb810d1bf55.tar
Data-structures-and-algorithms-dbd2a89e755ac4941f3afbf3bf78ecb810d1bf55.tar.gz
Data-structures-and-algorithms-dbd2a89e755ac4941f3afbf3bf78ecb810d1bf55.zip
Parent20af6cae13ae020bc167008bb4e52a4cf01d911b (diff)
Add pract03 readme, merge and partition implementations
1 files changed, 88 insertions, 0 deletions
-rw-r--r--Practicum/pract03/merge.cpp88
diff --git a/Practicum/pract03/merge.cpp b/Practicum/pract03/merge.cpp
new file mode 100644
index 0000000..68dfd5b
--- /dev/null
+++ b/Practicum/pract03/merge.cpp
@@ -0,0 +1,88 @@
+#include <iostream>
+#include <vector>
+
+// V. 1
+template<class RandomIt>
+void merge(RandomIt first1, RandomIt last1,
+ RandomIt first2, RandomIt last2,
+ RandomIt buff)
+{
+ for (; first1 != last1; ++buff)
+ {
+ if (first2 == last2)
+ {
+ for (; first1 != last1; ++first1, ++buff)
+ *buff = *first1;
+
+ return;
+ }
+
+ if (*first2 < *first1)
+ {
+ *buff = *first2;
+ ++first2;
+ }
+ else
+ {
+ *buff = *first1;
+ ++first1;
+ }
+ }
+
+ for (; first2 != last2; ++first2, ++buff)
+ *buff = *first2;
+}
+
+// V. 2
+template <class RandomIt>
+void merge(RandomIt first1, RandomIt last1,
+ RandomIt first2, RandomIt last2,
+ RandomIt buff)
+{
+ while (first1 != last1 && first2 != last2)
+ {
+ if (*first1 <= *first2)
+ {
+ *buff = *first1;
+ ++first1;
+ }
+ else
+ {
+ *buff = *first2;
+ ++first2;
+ }
+
+ ++buff;
+ }
+
+ while (first1 != last1)
+ {
+ *buff = *first1;
+ ++first1;
+ ++buff;
+ }
+
+ while (first2 != last2)
+ {
+ *buff = *first2;
+ ++first2;
+ ++buff;
+ }
+}
+
+int main()
+{
+ std::vector<int> v1;
+ for (int i = 1; i <= 5; i++)
+ v1.push_back(i);
+
+ for (int i = 3; i <= 8; i++)
+ v1.push_back(i);
+
+ std::vector<int> v(11);
+
+ merge(v1.begin(), v1.begin() + 5, v1.begin() + 5, v1.end(), v.begin());
+
+ for (int i = 0; i < 11; i++)
+ std::cout << v[i] << " ";
+}