-3

I would request you guys to suggest an efficient way to check if every odd element is greater than every even element in array in java, using just arrays

Thanks

Programmer
  • 29
  • 5

1 Answers1

4

Iterate over the array once, and keep track of the smallest odd element and the highest even element. Then check that the first is higher than the second (i.e. check that the minimum odd element is higher than the maximum even element).

You can even improve the algorithm to fail fast. At any point while iterating over the array, if the current smallest odd element becomes smaller than the current highest even element, you can quit the loop and return false.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • Doesn't check that _all_ odd elements are greater than _all_ even elements (e.g. `4 3 2 1` would pass the test you describe but `3 > 2` and `3` is in an even position) – Arc676 Nov 19 '15 at 11:44
  • 2
    @Arc676 it would check if `1`, the smallest odd, is greater then `4` the highest even. – SomeJavaGuy Nov 19 '15 at 11:48
  • The problem is how can i initialize the highest even element and smallest odd element holding variable. example array - {11, 4, 9, 2, 8} @Eran – Programmer Nov 19 '15 at 11:50
  • @Programmer Iterate through the array and find them. It's the first sentence of the answer. – Andy Turner Nov 19 '15 at 11:51
  • @Eran what if the array contains only even elements or only odd elements – Programmer Nov 19 '15 at 11:52
  • @Programmer [smallest](http://stackoverflow.com/questions/12122232/java-finding-smallest-number-in-an-array) and [highest](http://stackoverflow.com/questions/1806816/java-finding-the-highest-value-in-an-array). The addition from Eran is quite usefull since you could potentinally reduce the runtime from `O(n)` to something lower if the condition is already false at any point. – SomeJavaGuy Nov 19 '15 at 11:52
  • @Programmer You initialize the highest even element to a very small number (Integer.MIN_VALUE, assuming you are working with an int array) and the smallest old element to a very high number (Integer.MAX_VALUE). Then you update them as you iterate over the elements of the array. – Eran Nov 19 '15 at 11:53
  • @Programmer I thought you were asking about elements having odd vs. even index, but if you were referring to the odd/even values themselves, the same idea still works. – Eran Nov 19 '15 at 11:55
  • Thanks for the answer, question should be upvoted i guess, its not that bad question – Programmer Nov 19 '15 at 11:59
  • @Eran I need to ask some more questions on java Programs. Stackoverflow doesnot allow to ask such questions. Please help me with this, where shall i ask you questions? – Programmer Nov 20 '15 at 03:52
  • @Programmer Stack Overflow allows asking questions about Java programs. Just make sure your questions follow the rules. The important thing is to include the relevant code of whatever you are having trouble with. – Eran Nov 20 '15 at 08:30