Examples :
Input:
arr1[ ] = {1, 2, 6, 8, 5, 4, 7, 9, 10, 12}
Output:
The start and end indexes are 2 and 7
Here,
The subarray {6, 8, 5, 4,7} if sorted,
then the whole array will be sorted.
#include <bits/stdc++.h>
using namespace std;
void findSubarr(int arr[], int n)
{
int l = 0, r = n - 1, i, max, min;
// find the l index
for (l = 0; l < n - 1; l++)
{
if (arr[l] > arr[l + 1])
break;
}
if (l == n - 1)
{
cout << "The complete arr is sorted";
return;
}
// Find the ring index
for (r = n - 1; r > 0; r--)
{
if (arr[r] < arr[r - 1])
break;
}
// Find max and min
max = arr[l];
min = arr[l];
for (i = l + 1; i <= r; i++)
{
if (arr[i] > max)
max = arr[i];
if (arr[i] < min)
min = arr[i];
}
// reassign l
for (i = 0; i < l; i++)
{
if (arr[i] > min)
{
l = i;
break;
}
}
// reassign r
for (i = n - 1; i >= r + 1; i--)
{
if (arr[i] < max)
{
r = i;
break;
}
}
cout << "The l and r indexes are " << l << " and " << r;
return;
}
// Main function
int main()
{
int arr[100], N;
cout << "Enter Number of elements: ";
cin >> N;
for (int i = 0; i < N; i++)
{
cin >> arr[i];
}
findSubarr(arr, N);
return 0;
}
Output:
Enter Number of elements: 10
1 2 4 6 5 7 9 10 11 10
The l and r indexes are 3 and 9
0 Comments