-
Recursive Rotate Left
an exercise;
I want to write a recursive function that rotates left an integer array, i.e. the given array
1 2 3 4
will be
2 3 4 1
after the function executed.
for this I write
Code:
#include <iostream>
#include <iomanip>
using namespace std;
int vArray[] = {1,2,3,4,5,6,7,8,9};
const int vsize = 9;
void rotateLeft(int foo[], int size) {
if ( foo[1] == NULL )
foo[0] = *(foo - size);
else{
foo[0] = foo[1];
rotateLeft(&foo[1], --size);
}
}
int main() {
rotateLeft(vArray, vsize);
cout << "Element" << setw( 13 ) << "Value" << endl;
for(int i=0; i<vsize; ++i)
cout << setw( 7 ) << i << setw( 13 ) << vArray[ i ] << endl;
return 0;
}
But i couldn't handle with the base condition I think. Actually this code gives
Code:
Element Value
0 2
1 3
2 4
3 5
4 6
5 7
6 8
7 9
8 9
How can i take the value of first element and equalize the value of last element to it?
-
int n = foo[first_element];
Make a for loop that runs through the elements and puts them into the foo array in the i-1 place.
And then when the for loop has reached the end, just foo[last_element] = n;
And you're done.? :)
-
I need a recursive function, not iterative or not a loop
-
The recursive function would need three pieces of information:
the array,
the array size,
the current position in the array
I can think of a couple different methods:
Swap element n and element n+1 until n+1 > size
make a copy of element and put it into element n-1 working backwards from the end
-
yes!
why couldn't i think of it, swapping two adjacent elements would work,
Thanks Thantos,
I will try this solution and post it here.
-
Re:
And the solution is
Code:
#include <iostream>
#include <iomanip>
using namespace std;
int vArray[] = {1,2,3,4,5,6,7,8,9};
const int vsize = 9;
void rotateLeft(int foo[], int size) {
int temp;
if (size == 1);
else{
temp = foo[0];
foo[0] = foo[1];
foo[1] = temp;
rotateLeft(&foo[1], --size);
}
}
int main() {
rotateLeft(vArray, vsize);
cout << "Element" << setw( 13 ) << "Value" << endl;
for(int i=0; i<vsize; ++i)
cout << setw( 7 ) << i << setw( 13 ) << vArray[ i ] << endl;
return 0;
}