Why doesn't this cause infinite loop b/c if I had an array of let's say 2 elems, and I set the wrong base case as such, wouldn't front be an index that goes past last index in array?
1 2 3 4 5 6 7 8 9 10 11 12 13 14
void reverse(int* list, int front, int end)//main calls fcn w/ arguments: &list[0], 0, (size - 1)
{
if ( front <= end )//Q: why doesn't this cause infinite loop?
return;
else
{
//swap current front w/ current end elem
int tmp = list[front];
list[front] = list[end];
list[end] = tmp;
reverse(list, front + 1, end - 1);
}
}
the correct base case is: if ( front >= end ) but I'm curious as why it compiles and when I print the array, it still prints: 1,2, rather than be an infinite loop.
1 2 3 4 5 6 7 8 9 10
int main()
{
int list[] = {1,2};
reverse(list, 0, 1);
for ( int i = 0; i < 2; ++i)
cout << list[i] << " , ";
return 0;
}
This seems simple, but how do I get the function to output the new reversed array?
why would it cause an infinite loop? the value you are calling with are 0 and (length-1) so if (front <= end) condition is always satisfied whatever be your array and reverse returns without doing anything, hence the array is printed as such even after the call.