fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. System.out.println( Ideone.isSorted( 1 , 2 , 1 ) ) ; // Should be 0.
  13. System.out.println( Ideone.isSorted( 1 , 2 , 3 ) ) ; // Should be 1.
  14. System.out.println( Ideone.isSorted( 3 , 2 , 1 ) ) ; // Should be -1.
  15.  
  16. System.out.println( Ideone.isSorted( -7 , 0 , 42 ) ) ; // Should be 1.
  17. System.out.println( Ideone.isSorted( 42 , 0 , -7 ) ) ; // Should be -1.
  18. }
  19.  
  20. // Source - https://stackoverflow.com/a/79844791
  21. // Posted by Ryan Hilbert, modified by community. See post 'Timeline' for change history
  22. // Retrieved 2025-12-12, License - CC BY-SA 4.0
  23. public static byte isSorted(int... array){
  24. if (array == null || array.length <= 0) return 0; // no elements
  25. int previous = array[0];
  26. boolean ascended = false, descended = false;
  27. for(int element: array){
  28. if (element > previous) ascended = true;
  29. if (element < previous) descended = true;
  30. if (ascended && descended) return 0; // Unsorted. No need to continue. Exit `for` loop early.
  31. previous = element;
  32. }
  33. if (ascended) return 1; // Sorted in ascending order.
  34. if (descended) return -1; // Sorted in descending order.
  35. return 0; // All elements equal.
  36. }
  37. }
Success #stdin #stdout 0.09s 54524KB
stdin
Standard input is empty
stdout
0
1
-1
1
-1