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 <iostream>
#include <vector>
#include <algorithm>
using big_int = long long;
struct answer {
std::size_t count;
big_int first_element;
big_int last_element;
};
template<class T>
answer bubble_sort(std::vector<T> &v) {
std::size_t swap_count = 0;
for (int i = 0; i < v.size(); i++) {
for (int j = 0; j < v.size() - 1; j++) {
if (v[j] > 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 >> n;
std::vector<big_int> v(n);
for (int i=0; i<n; i++) {
std::cin >> v[i];
}
auto answer = bubble_sort(v);
std::cout << "Array is sorted in " << answer.count << " swaps.\n"
<< "First Element: " << answer.first_element << "\n"
<< "Last Element: " << answer.last_element;
}