0

Create a function bool isOrdered(int numArray[], unsigned size)

It must return true if numbers are ordered and false if not. Being the same number as the previous one doesnt return false. {1,2,3,3,4} should return true. {1,2,3,3,2} should return false. {-8,-4,-3,-2,-1} should return true. EDIT: {-1,-2,-3,-3,-4} should return true.

2nd Jul 2016, 6:32 PM
Garme Kain
Garme Kain - avatar
3 ответов
0
void isOrdered(int numArray[], unsigned size ) { int i,d =0; for(i=0;i<size-1;i++) { if(numArray[i]<numArray[i+1]) { d++; continue; } else d=-1; } if(d> 0 ) cout<<"\n True "; else cout<<"\n False "; } I think this should answer your problem .
3rd Jul 2016, 3:32 PM
shubham sharma
0
Your code return true for {1,2,0,1,2}, which is an array that is not ordered, and false for {-1,-2,-3,-4,-5} or {2,2,2,2,2}. Another answer: bool ordered(int arr[], unsigned sz) { int dir = 0; for(unsigned i = 0; i < sz-1; i++) { if(arr[i] == arr[i + 1]) continue; if(dir) if(dir != (arr[i] < arr[i + 1] ? 1 : -1)) return false; else if(arr[i] < arr[i + 1]) dir = 1; else dir = -1; } return true; }
3rd Jul 2016, 4:36 PM
Garme Kain
Garme Kain - avatar
0
Also, the continue keyword used where you used it, doesnt make sense because every time d++ is executed it is the last line of the for loop, so it is the same as not putting anything (maybe even worse, because the compiler needs to compile one more line of code).
3rd Jul 2016, 4:49 PM
Garme Kain
Garme Kain - avatar