diff --git a/ex02/src/PmergeMe.hpp b/ex02/src/PmergeMe.hpp index 5575380..3e9626b 100644 --- a/ex02/src/PmergeMe.hpp +++ b/ex02/src/PmergeMe.hpp @@ -1,5 +1,6 @@ #pragma once +#include #include #include #include @@ -13,10 +14,11 @@ std::pair* create_pairs(const T& array, size_t len) { std::pair* pairs = new std::pair[len]; - for (size_t i = 0; i != len; i++) + for (size_t i = 0; i < len; i++) { pairs[i].second = array[i * 2]; - pairs[i].first = array[i * 2 + 1]; + if (array.size() > i * 2 + 1) + pairs[i].first = array[i * 2 + 1]; } if (len % 2) pairs[len - 1].first = pairs[len - 1].second; @@ -24,16 +26,40 @@ std::pair* create_pairs(const T& array, size_t len) } template -void binary_search(std::pair* pairs, size_t len, T& array) -{ - (void) pairs; - (void) array; - std::vector bozo; - for (size_t i = 0; i < len; i++) +size_t binary_search(const T& array, size_t start, size_t end, int value) { + if (array[end] < value) + return end; + + while (true) { + int mid = start + ((end - start) / 2); + int min_value = array[mid]; + if (min_value == value || end - start <= 1) + { + if (min_value < value) + return mid + 1; + return mid; + } + else if (min_value < value) + start = mid; + else if (min_value > value) + end = mid; } -} +} + +template +void insert_sort(const std::pair* pairs, size_t len, T& array) +{ + for (size_t i = 1; i < len; i++) + { + array.push_back(pairs[i].first); + if (pairs[i].first == pairs[i].second) + continue; + ssize_t index = binary_search(array, 0, array.size() - 1, pairs[i].second); + array.insert(array.begin() + index, pairs[i].second); + } +} template void PmergeMe(T& array) @@ -42,7 +68,10 @@ void PmergeMe(T& array) std::pair* pairs = create_pairs(array, len); sort_pair(pairs, len); sort_pairs(pairs, len); - std::cout << pairs; array.clear(); - binary_search(pairs, len, array); + array.push_back(pairs[0].second); + if (pairs[0].second != pairs[0].first) + array.push_back(pairs[0].first); + insert_sort(pairs, len, array); + delete[] pairs; } \ No newline at end of file diff --git a/ex02/src/main.cpp b/ex02/src/main.cpp index be24b23..8003c8e 100644 --- a/ex02/src/main.cpp +++ b/ex02/src/main.cpp @@ -1,4 +1,5 @@ #include "PmergeMe.hpp" +#include #include #include #include @@ -15,10 +16,9 @@ int main(int ac, char** av) std::cout << std::endl; PmergeMe(input); std::cout << "After: "; - for (int i = 1; i != ac; i++) + for (size_t i = 0; i != input.size(); i++) { - input[i - 1] = atoi(av[i]); - std::cout << av[i] << " "; + std::cout << input[i] << " "; } std::cout << std::endl; } \ No newline at end of file