Open In App

Circularly Sorted Array (Sorted and Rotated Array)

Last Updated : 16 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Circularly sorted arrays are arrays that are sorted in ascending or descending order and then rotated by a number of steps.

Let us take an example to know more about circularly sorted arrays:

Consider an array: arr[] = {23, 34, 45, 12, 17, 19}
The elements here, {12, 17, 19, 23, 34, 45} are sorted ‘In-order’ but they are rotated to the left by 3 times.

Ascending circularly sorted array:

  • Consider an array sorted in ascending order: arr[] = {12, 17, 19, 23, 34, 45} 
  • If the above array is rotated by 3 steps to the left, then the resultant array will be ascending circularly sorted array: {23, 34, 45, 12, 17, 19}

Descending circularly sorted array:

  • Consider an array sorted in descending order: arr[] = {35, 26, 11, 9, 5, 3} 
  • If the above array is rotated by 3 steps to the left, then the resultant array will be descending circularly sorted array: {9, 5, 3, 35, 26, 11}

Let us check through the below problem whether the given array is circularly sorted or not:

Problem Statement:

Given an array arr[] of length N, the task is to check whether the given array is circularly sorted or not, we need to check whether the given array is the rotated form of the sorted array. 

  • In ascending circularly sorted array, there will be at most one case where the element just before the current element will be greater than the current element i.e., arr[ i – 1 ] > arr[ i ]. If there is no such case, then we consider the array as circularly sorted, this is the result of a rotation by N steps. On the other hand, if there is only one such case; we then make sure that the first element of the array is greater than the last one i.e., arr[0] > arr[N-1].
  •  So we need to count the total existence of arr[ i – 1 ] > arr[ i ] cases and if the count is 1 with arr[ 0 ] < arr[ N-1 ] or if the count is greater than 1 then the result will be false else the result will be true meaning that the array is circularly sorted.

Below is the implementation for the above approach: 

C++




// CPP program to check whether
// the array is circularly sorted
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to check whether
// array is circularly sorted
bool checkCircularSorted(int arr[], int n)
{
 
    // cnt variable will store count of
    // arr[i-1] > arr[i]
    int cnt = 0;
 
    for (int i = 1; i < n; i++) {
 
        // increase cnt if arr[i-1] > arr[i]
        if (arr[i - 1] > arr[i]) {
            cnt++;
        }
    }
 
    // if cnt > 1 then false
    // else true
    if (cnt == 1) {
        // check first and last element.
        return arr[0] > arr[n-1];
    }
    else {
        return false;
    }
}
 
// Driver code
int main()
{
 
    // Given array
    int arr[] = { 23, 34, 45, 12, 17, 19 };
 
    // size of array
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Calling function to check
    // cirularly sorted array
    bool result = checkCircularSorted(arr, N);
 
    // Print result
    if (result) {
        cout << "Array is circularly sorted";
    }
    else {
        cout << "Array is not circularly sorted";
    }
}


Java




// Java program to check whether
// the array is circularly sorted
 
public class Main {
 
    // Method to check whether
    // array is circularly sorted
    public static boolean checkCircularSorted(int arr[])
    {
        // cnt variable will store
        // count of arr[i-1] > arr[i]
        int cnt = 0;
 
        for (int i = 1; i < arr.length; i++) {
            // increase cnt if arr[i-1] > arr[i]
            if (arr[i - 1] > arr[i]) {
                cnt++;
            }
        }
        // if cnt > 1 then false
        // else true
        if (cnt == 1) {
            // check first and last element.
            return arr[0] > arr[arr.length-1];
        }
        else {
            return false;
        }
    }
 
    // Driver code
    public static void main(String args[])
    {
        // Given array
        int arr[] = { 23, 34, 45, 12, 17, 19 };
 
        // calling method to check
        // cirularly sorted array
        boolean result = checkCircularSorted(arr);
 
        // print result
        if (result == true) {
            System.out.println(
                "Array is circularly sorted");
        }
        else {
            System.out.println(
                "Array is not circularly sorted");
        }
    }
}


Python




#  Python program to check whether
#  the array is circularly sorted
 
# Function to check whether
# array is circularly sorted
 
 
def checkCircularSorted(arr):
    # cnt variable will store count of
    # arr[i-1] > arr[i]
    cnt = 0
    n = len(arr)
    for i in range(1, n):
 
        # increase cnt if arr[i-1] > arr[i]
        if arr[i - 1] > arr[i]:
            cnt += 1
 
    # if cnt > 1 then false
    # else true
    if cnt == 1:
        # check first and last element.
        return arr[0] > arr[n-1];
    else:
        return False
 
 
# Driver code
if __name__ == '__main__':
    # Given array
    arr = [23, 34, 45, 12, 17, 19]
 
    # Calling function to check
    # cirularly sorted array
    result = checkCircularSorted(arr)
 
    # Print result
    if result == True:
        print("Array is circularly sorted")
    else:
        print("Array is not circularly sorted")
 
# This code has been contributed by Sachin Sahara (sachin801)


C#




// C# program to check whether
// the array is circularly sorted
using System;
 
public class GFG {
 
  // Method to check whether
  // array is circularly sorted
  public static bool checkCircularSorted(int []arr)
  {
    // cnt variable will store
    // count of arr[i-1] > arr[i]
    int cnt = 0;
 
    for (int i = 1; i < arr.Length; i++) {
      // increase cnt if arr[i-1] > arr[i]
      if (arr[i - 1] > arr[i]) {
        cnt++;
      }
    }
    // if cnt > 1 then false
    // else true
    if (cnt == 1) {
      // check first and last element.
      return arr[0] > arr[arr.Length-1];
    }
    else {
      return false;
    }
  }
 
  // Driver code
  public static void Main(string []args)
  {
    // Given array
    int []arr = { 23, 34, 45, 12, 17, 19 };
 
    // calling method to check
    // cirularly sorted array
    bool result = checkCircularSorted(arr);
 
    // print result
    if (result == true) {
      Console.WriteLine("Array is circularly sorted");
    }
    else {
      Console.WriteLine("Array is not circularly sorted");
    }
  }
}
 
// This code is contributed by AnkThon


Javascript




<script>
 
// JavaScript program to check whether
// the array is circularly sorted
 
 
// Function to check whether
// array is circularly sorted
function checkCircularSorted(arr, n)
{
 
    // cnt variable will store count of
    // arr[i-1] > arr[i]
    let cnt = 0;
 
    for (let i = 1; i < n; i++) {
 
        // increase cnt if arr[i-1] > arr[i]
        if (arr[i - 1] > arr[i]) {
            cnt++;
        }
    }
 
    // if cnt > 1 then false
    // else true
    if (cnt == 1) {
        // check first and last element.
        return arr[0] > arr[n-1];
    }
    else {
        return false;
    }
}
 
// Driver code
 
// Given array
let arr = [ 23, 34, 45, 12, 17, 19 ];
 
// size of array
let N = arr.length;
 
// Calling function to check
// cirularly sorted array
let result = checkCircularSorted(arr, N);
 
// Print result
if (result) {
    document.write("Array is circularly sorted","</br>");
}
else {
    document.write("Array is not circularly sorted","</br>");
}
 
// This code is contributed by shinjanpatra
 
</script>


Output

Array is circularly sorted

Time Complexity: O(n) 

Auxiliary Space: O(1)

Similarly, we can do the above operation for descending circularly sorted array. In this case we need to consider the count of the case where, arr [i-1] < arr[i]

Related articles:



Similar Reads

Modify a string by circularly shifting each character to the right by respective frequencies
Given a string S consisting of lowercase English alphabets, the task is to right shift each character of the given string S circularly by its frequency. Circular shifting of characters refers to shifting character 'z' to 'a', as its next character. Examples: Input: S = "geeksforgeeks"Output: iiimugpsiiimu Explanation:Following changes are made on t
6 min read
Search an element in a sorted and rotated array with duplicates
Given an array arr[] which is sorted and rotated, the task is to find an element in the rotated array (with duplicates) in O(log n) time. Note: Print the index where the key exists. In case of multiple answer print any of them Examples: Input: arr[] = {3, 3, 3, 1, 2, 3}, key = 3 Output: 0 arr[0] = 3 Input: arr[] = {3, 3, 3, 1, 2, 3}, key = 11 Outpu
14 min read
C++ Program for Check if an array is sorted and rotated
Given an array of N distinct integers. The task is to write a program to check if this array is sorted and rotated counter-clockwise. A sorted array is not considered as sorted and rotated, i.e., there should at least one rotation.Examples: Input : arr[] = { 3, 4, 5, 1, 2 } Output : YES The above array is sorted and rotated. Sorted array: {1, 2, 3,
5 min read
Java Program for Check if an array is sorted and rotated
Given an array of N distinct integers. The task is to write a program to check if this array is sorted and rotated counter-clockwise. A sorted array is not considered as sorted and rotated, i.e., there should at least one rotation.Examples: Input : arr[] = { 3, 4, 5, 1, 2 } Output : YES The above array is sorted and rotated. Sorted array: {1, 2, 3,
3 min read
Python3 Program for Check if an array is sorted and rotated
Given an array of N distinct integers. The task is to write a program to check if this array is sorted and rotated counter-clockwise. A sorted array is not considered as sorted and rotated, i.e., there should at least one rotation.Examples: Input : arr[] = { 3, 4, 5, 1, 2 } Output : YES The above array is sorted and rotated. Sorted array: {1, 2, 3,
3 min read
Maximum element in a sorted and rotated array
Given a sorted array arr[] of distinct elements which is rotated at some unknown point, the task is to find the maximum element in it.Examples: Input: arr[] = {3, 4, 5, 1, 2} Output: 5Input: arr[] = {1, 2, 3} Output: 3 Approach: A simple solution is to traverse the complete array and find maximum. This solution requires O(n) time. We can do it in O
6 min read
Check if an array is sorted and rotated using Binary Search
Pre-requisite: Check if an array is sorted and rotated using Linear SearchGiven an array arr[] of N distinct integers, the task is to check if this array is sorted when rotated counter-clockwise. A sorted array is not considered sorted and rotated, i.e., there should at least one rotation. Examples: Input: arr[] = { 3, 4, 5, 1, 2 } Output: true Exp
11 min read
C++ Program for Given a sorted and rotated array, find if there is a pair with a given sum
Given an array that is sorted and then rotated around an unknown point. Find if the array has a pair with a given sum 'x'. It may be assumed that all elements in the array are distinct. Examples : Input: arr[] = {11, 15, 6, 8, 9, 10}, x = 16 Output: true There is a pair (6, 10) with sum 16 Input: arr[] = {11, 15, 26, 38, 9, 10}, x = 35 Output: true
6 min read
Javascript Program for Check if an array is sorted and rotated
Given an array of N distinct integers. The task is to write a program to check if this array is sorted and rotated counter-clockwise. A sorted array is not considered as sorted and rotated, i.e., there should at least one rotation.Examples: Input : arr[] = { 3, 4, 5, 1, 2 } Output : YES The above array is sorted and rotated. Sorted array: {1, 2, 3,
3 min read
C Program for Given a sorted and rotated array, find if there is a pair with a given sum
Write a C program for a given array arr[] of distinct elements size N that is sorted and then rotated around an unknown point, the task is to check if the array has a pair with a given sum X. Examples : Input: arr[] = {11, 15, 6, 8, 9, 10}, x = 16Output: trueExplanation: There is a pair (6, 10) with sum 16 Input: arr[] = {11, 15, 26, 38, 9, 10}, x
7 min read
Article Tags :
Practice Tags :