

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find the Rotation Count in Rotated Sorted array in C++
Consider we have an array, which is rotated sorted array. We have to find number of rotations are required to sort the array. (We will consider rotation right to left.)
Suppose the array is like: {15, 17, 1, 2, 6, 11}, then we have to rotate the array two times to sort. The final order will be {1, 2, 6, 11, 15, 17}. Here output is 2.
The logic is simple. If we notice, we can see that the number of rotation is same as the value of index of minimum element. So if we get the minimum element, then its index will be the result.
Example
#include <iostream> using namespace std; int getMinIndex(int arr[], int n){ int index = 0; for(int i = 1; i<n; i++){ if(arr[i] < arr[index]){ index = i; } } return index; } int countNumberOfRotations(int arr[], int n){ return getMinIndex(arr, n); } int main() { int arr[] = {15, 17, 1, 2, 6, 11}; int n = sizeof(arr)/sizeof(arr[0]); cout << "Number of required rotations: " << countNumberOfRotations(arr, n); }
Output
Number of required rotations: 2
- Related Questions & Answers
- Find Minimum in Rotated Sorted Array in C++
- Find Minimum in Rotated Sorted Array II in C++
- Search in Rotated Sorted Array in Python
- Search in Rotated Sorted Array II in C++
- Search in Rotated Sorted Array II in Python
- Count rotations in sorted and rotated linked list in C++
- Maximum element in a sorted and rotated array in C++
- How to find the number of times array is rotated in the sorted array by recursion using C#?
- Check if an array is sorted and rotated in Python
- Check if an array is sorted and rotated in C++
- Count elements less than or equal to a given value in a sorted rotated array in C++
- Finding smallest element in a sorted array which is rotated in JavaScript
- Program to check whether an array Is sorted and rotated in Python
- Absolute distinct count in a sorted array?
- Count smaller elements in sorted array in C++
Advertisements