Skip to content

Commit 0b0cdf3

Browse files
committed
Rotation Count in Rotated Sorted Array
1 parent ecdadb7 commit 0b0cdf3

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

README.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,3 +193,7 @@ This is a repository containing various C++ Programs to understand the basic con
193193

194194
C++ Code for checking whether two given strings are anagrams of each other.
195195

196+
197+
* [Rotation Count in a Rotated Sorted Array](https://github.com/altruistcoder/Data-Structures/blob/master/rotation_count.cpp):
198+
199+
C++ Code for finding the rotation count in a rotated sorted array.

rotation_count.cpp

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
#include<bits/stdc++.h>
2+
using namespace std;
3+
4+
int countRotations(int a[], int low, int high)
5+
{
6+
if (high < low)
7+
return 0;
8+
if (high == low)
9+
return low;
10+
int mid=low+(high-low)/2;
11+
if (mid < high && a[mid+1] < a[mid])
12+
return (mid+1);
13+
if (mid > low && a[mid] < a[mid-1])
14+
return mid;
15+
if (a[high] > a[mid])
16+
return countRotations(a, low, mid-1);
17+
return countRotations(a, mid+1, high);
18+
}
19+
20+
int main()
21+
{
22+
int n, a[100];
23+
cout<<"Enter the size of the array: ";
24+
cin>>n;
25+
cout<<"Enter the elements of the array: ";
26+
for(int i=0;i<n;i++)
27+
cin>>a[i];
28+
cout<<"The rotation count of the given rotated sorted array is: "<<countRotations(a, 0, n-1);
29+
return 0;
30+
}

0 commit comments

Comments
 (0)