I tried reversing a vector through a divide et impera algorithm. Here's my code:
#include <iostream>
#include <vector>
using namespace std;
//prototype
void Reverse (std::vector<int> &v, int left, int right);
//helper function
void Switch(int &x, int &y)
{
int aux = x;
x = y;
y = aux;
}
int main()
{
vector <int> v;
int n; cout << "n="; cin >> n;
for (int i = 0; i < n; i++){
cout << "v[" << i <<"]=";
int input;
cin >> input;
v.push_back(input);
}
Reverse(v, 0, v.size()-1);
for (int i = 0; i < n; i++)
cout << v[i] << " ";
return 0;
}
void Reverse (std::vector<int> &v, int left, int right)
{
int mid = (left + right) / 2;
if (left == right + 1){
Switch(v[left], v[right]);
}
else{
Reverse(v, left, mid-1);
Reverse(v, mid, right);
}
}
It probably gives me an infinite loop because my program never returns when I compile it and I get a not responding error. What's the issue with it? Is it because I only switch the two elements at the base case and not two entire vectors?