Simple Bubble Sort swap counter C++ This is the solution for a simple challenge from Hackerrank.I am just trying to solve Sorting: Bubble Sort Problem on HackerRank.

We are asked to count the number of swaps performed during a bubble sort and to print the first and last item of the ordered vector.

Sample input

3
3 2 1


First line is the number of elements in the vector, the second line is the vector

Expected output

Array is sorted in 3 swaps.
First Element: 1
Last Element: 3


Code

I've implemented my solution in C++ and would love to hear what your feedback and what could I have done cleaner

#include &lt;iostream&gt;
#include &lt;vector&gt;
#include &lt;algorithm&gt;

using big_int = long long;

struct answer {
    std::size_t count;
    big_int first_element;
    big_int last_element;
};

template&lt;class T&gt;
answer bubble_sort(std::vector&lt;T&gt; &amp;v) {
    std::size_t swap_count = 0;
    for (int i = 0; i &lt; v.size(); i++) {
        for (int j = 0; j &lt; v.size() - 1; j++) {
            if (v[j] &gt; v[j + 1]) {
                std::swap(v[j], v[j + 1]);
                swap_count++;
            }
        }
    }
    return answer{swap_count, v[0], v[v.size()-1]};
}

int main(int argc, char** argv) {
    int n;
    std::cin &gt;&gt; n;
    std::vector&lt;big_int&gt; v(n);
    for (int i=0; i&lt;n; i++) {
        std::cin &gt;&gt; v[i];
    }

    auto answer = bubble_sort(v);
    std::cout &lt;&lt; "Array is sorted in " &lt;&lt; answer.count         &lt;&lt; " swaps.\n"  
              &lt;&lt; "First Element: "     &lt;&lt; answer.first_element &lt;&lt; "\n"
              &lt;&lt; "Last Element: "      &lt;&lt; answer.last_element;

}
Your answer should also be a template struct. It contains first and last element of type big_int but in the bubble _sort function it is constructed with template argument type T.

template&lt;class T&gt;
struct answer {
    std::size_t count;
    T first_element;
    T last_element;
};


But actually maybe the structure Is redundant because first And last element can Always easily be accessed inside the sorted container. Or it could at least contain just references to those elements instead of their copies in case the template argument T is something more complex then long long.

auto count = bubble_sort(v);
auto &amp; first = v[0];
auto &amp; last = v[v.size - 1];


Further instead of accepting vector&lt;T&gt;, you could accept two iterators of template argument type as Is common with many standard functions and allows to work not only for any type of container but also for just a range within a container.

template&lt;class Iterator&gt;
std::size_t bubble_sort(Iterator from, Iterator to);

// ...

auto count = bubble_sort(v.begin(), v.end());