import java.io.*; class GFG { // Function to check if an array is // Sorted and rotated clockwise static boolean checkIfSortRotated(int arr[], int n) { // Initializing two variables x,y as zero. int x = 0, y = 0; // Traversing array 0 to last element. // n-1 is taken as we used i+1. for (int i = 0; i < n - 1; i++) { if (arr[i] < arr[i + 1]) x++; else y++; } // If till now both x,y are greater // then 1 means array is not sorted. // If both any of x,y is zero means // array is not rotated. if (x == 1 || y == 1) { // Checking for last element with first. if (arr[n - 1] < arr[0]) x++; else y++; // Checking for final result. if (x == 1 || y == 1) return true; } // If still not true then definitely false. return false; } // Driver code public static void main(String[] args) { int arr[] = { 5, 1, 2, 3, 4 }; int n = arr.length; // Function Call boolean x = checkIfSortRotated(arr, n); if (x == true) System.out.println("YES"); else System.out.println("NO"); } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter