void swap(int& a,int& b){
int tmp;
tmp = a;
a = b;
b = tmp;
}
... and with templates
1 2 3 4 5 6 7
template <typename T>
void swap(T& a, T& b){
T tmp;
tmp = a;
a = b;
b = tmp;
}
... and using the copy constructor
1 2 3 4 5 6
template <typename T>
void swap(T& a, T& b){
T tmp = a; // copy construction
a = b;
b = tmp;
}
... and in C++11 with move
1 2 3 4 5 6
template <typename T>
void swap(T& a, T& b){
T tmp = std::move(a);
a = std::move(b);
b = std::move(tmp);
}
The last version is basically the std::swap function
You can go with any of those, use one you understand or learn how the others work, it's up to you :)
One way to find mistakes is to use print out data.
I used "GOT HERE" to show it never got there.
And then placed a print out in the algo routine and it becomes apparent it is caught in a loop.
So now you step through the loop to see why.
It is kind of fun like being a detective and very satisfying when you figure it out although probably not as satisfying as having it run perfect first time :)
First of all using int to return success/failure is a C way. You are not actually using C++. In fact your whole code is in C.
Ok, now to the actual problems.
If prod is 0 when you called your function, it will stay that way. Nothing changes it to 1. this stems from next problem:
Global prod variable. If you have global variable, you should stop and reconcider "should I have it at all? How can I get rid of it?"
In your case that variable brings state to order function. Now it depends on result of previous execution.
So your function is better be named "was_unsorted_array_passed_at_any_time" right now.
MiiNiPaa,
Most glaring mistake to an experienced c++ programmer :)
Beginners are lucky to have someone like you to help them out.
My interest was as someone learning c++ to see if I can figure out the problems to see what I still have to learn.
It became obvious to me that
while(order(v)==0);
was always true and thus went on forever
At a glance the purpose of order(), that is, the algorithm isn't clear to me.