Given an array of numbers arr and a window of size k, print out the median of each window of size k starting from the left and moving right by one position each time.
For example, given the following array and k = 3:
[-1, 5, 13, 8, 2, 3, 3, 1]
Your function should print out the following:
5 <- median of [-1, 5, 13]
8 <- median of [5, 13, 8]
8 <- median of [13, 8, 2]
3 <- median of [8, 2, 3]
3 <- median of [2, 3, 3]
3 <- median of [3, 3, 1]Recall that the median of an even-sized list is the average of the two middle numbers.
Is there any improvement possible in this implementation?
#include <iostream>
#include <vector>
#include <array>
#include <algorithm>
template <typename T>
struct range
{
auto begin()const {return a; }
auto end()const {return b;}
T a,b;
};
range<const int*>make_range(const int* begin, const int* end)
{
return {begin, end};
}
range<const int *> make_window(const std::vector<int>& vec, size_t start, size_t end)
{
return make_range(vec.data() + start, vec.data() + end);
}
int median(int arr[], size_t N)
{
//sort the array
std::sort(arr, arr + N);
if(N % 2 == 0)
return (arr[N/2 - 1] + arr[N/2])/2;
return arr[N/2];
}
int main(){
const auto window_length = 3;
std::vector<int> input{-1, 5, 13, 8, 2, 3, 3, 1};
const auto end_length = input.size() - window_length;
std::array<int, window_length> arr{};
for(size_t i(0); i < end_length; i++)
{
int counter (0);
const auto window = make_window(input, i, i + window_length);
for(const auto& value : window)
{
std::cout << value << ' ';
arr[counter++] = value;
}
int result = median(arr.data(), arr.size());
counter = 0;
std::cout << "\nmedian " << result << '\n';
std::cout << '\n';
}
return EXIT_SUCCESS;
}
N
andk
? \$\endgroup\$