Check If an Array is Sorted and Rotated in C++



A sorted and rotated array is an array that is sorted in ascending or descending order and then rotated either left or right by a specific number of elements. There should exist exactly one pivot point around which the array is rotated. The array can be said to be split into two halves and each half is a sorted array. For example: {5, 6, 7, 1, 2, 3} is a sorted and rotated array and {5, 6, 7, 8, 2, 5, 4, 5} is not a sorted and rotated array. In this article, our task is to check if the given array is sorted and rotated array.

Example

Here is an example of a sorted and rotated array:

Input:
arr = {5, 6, 7, 1, 2, 3, 4}

Output:
True

The explanation of the above example is as follows:

counter = 0
a[0] = 5, a[0+1] = 6; Since, a[0] < a[1], counter = 0
a[1] = 6, a[1+1] = 7; Since, a[1] < a[2], counter = 0
a[2] = 7, a[2+1] = 1; Since, a[2] > a[3], counter = 1
a[3] = 1, a[3+1] = 2; Since, a[3] < a[4], counter = 1
a[4] = 2, a[4+1] = 3; Since, a[4] < a[5], counter = 1
a[5] = 3, a[5+1] = 4; Since, a[5] < a[6], counter = 1
a[6] = 4, a[(6+1)%7] = a[0] = 5; Since a[6] < a[0], counter = 1

counter = 1 => The array is sorted and rotated

Steps for Checking if Array is Sorted and Rotated

The following steps check if the given array is sorted and rotated or not:

  • First, we have declared an array.
  • A Boolean function check() is defined that returns true if the array is sorted and rotated otherwise it returns false.
  • Using for loop, we iterate over the array and count the number of elements such that the current element of the array is greater than its next element i.e., (arr[i] > arr[i+1]%n).
  • If the count is '1', then return True, otherwise return False. Here, True represents that the array is sorted and rotated.

C++ Program to Check if Array is Sorted and Rotated

The following code implements the above steps for checking if the given array is sorted and rotated or not.

#include <bits/stdc++.h>
using namespace std;
bool check(int * arr, int n) {
   int counter = 0;
   for (int i = 0; i < n; i++) {
      if (arr[i] > arr[(i + 1) % n])
         counter++;
   }
   return (counter <= 1);
}
int main() {
   int arr[] = {5,6,7,1,2,3,4};
   int n = sizeof(arr) / sizeof(int);
   cout << "The array is: ";
   for (int i = 0; i < n; i++) {
      cout << arr[i] << " ";
   }
    cout << endl;
   if (check(arr, n)) {
      cout << "True" << endl;
   } else {
      cout << "False" << endl;
   }
   return 0;
}

The output of the above code is as follows:

The array is: 5 6 7 1 2 3 4 
True
Updated on: 2025-06-06T19:15:03+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started