javaalgorithmintegeralternating

How can I tell if an array of integers is an alternating array?


I want to tell if an array of integers is alternating. in JAVA.

For example:

a[]={1,-1,1,-1,1,-1}  --> true
a[]={-1,1,-1,1,-1}    --> true
a[]={1,-4,1-6,1}      --> true
a[]={1,1,1,14,5,3,2}  --> false

I have started to write some code that uses flags. For example if the current_is_positive=0 and else = 1, but I'm not getting anywhere. What is a good way to achieve this effect?


Solution

  • I think you mean alternating in sign, i.e. positive number, negative number, positive number, etc.? You could use the following strategy:

    Skip the first element.

    For every other element, compare its sign with the sign of the previous element:

    As this sounds like a homework assignment, I'll leave it upto you to write the appropriate code in Java.