Examples:
Input:
arr[ ]= {4 , 5, 1, 2, 3}
Output:
Minimum element: 1
Input:
arr[ ]= {50,40, 10, 20, 30}
Output:
rotation count : 10
#include <bits/stdc++.h>
using namespace std;
// Function to find the minimum value
// in sorted and rotated arr
int findMin(int arr[], int l, int r)
{
// if arr is not rotated
if (r < l)
return arr[0];
// if arr contains only one element
if (r == l)
return arr[l];
// Find mid
int mid = l + (r - l) / 2;
// check if minimum element is present at
// mid+1 and mid-1
if (mid < r && arr[mid + 1] < arr[mid])
return arr[mid + 1];
if (mid > l && arr[mid] < arr[mid - 1])
return arr[mid];
// if minimum present in the left half
if (arr[r] > arr[mid])
return findMin(arr, l, mid - 1);
// if minimum present in the right half
return findMin(arr, mid + 1, r);
}
// Main function
int main()
{
int arr[100], N, element;
cout << "Enter Number of elements: ";
cin >> N;
for (int i = 0; i < N; i++) {
cin >> arr[i];
}
cout << "Minimum element: " << findMin(arr, 0, N - 1);
return 0;
}
Output:
Enter Number of elements: 5
4 5 1 2 3
Minimum element: 1
0 Comments