Examples:
1.Input: n = 7
7 9 10 8 11 12 13
Output : 3
Here, 9 10 8 unordered sub-array.
2.Input : n = 7
1 2 3 4 5 6 7
Output : 0
Here, the Array is in increasing order.
3.Input : n = 7
7 6 5 4 3 2 1
Output : 0
Here, the Array is in decreasing order.
#include <bits/stdc++.h>
using namespace std;
// Function to check whether arr is increasing
bool checkIncreasing(int arr[], int n)
{
for (int i = 0; i < n - 1; i++)
if (arr[i] >= arr[i + 1])
return false;
return true;
}
// Function to check whether arr is decreasing
bool checkDecreasing(int arr[], int n)
{
for (int i = 0; i < n - 1; i++)
if (arr[i] < arr[i + 1])
return false;
return true;
}
// Function to check for shortest unordered
int unorderedShortest(int arr[], int n)
{
// if increase or decreasing,
// return 0 else 3
if (checkIncreasing(arr, n) == true || checkDecreasing(arr, n) == true)
return 0;
else
return 3;
}
// 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];
}
cout << "Shortest un-ordered sub-arr: " << unorderedShortest(arr, n);
return 0;
}
Output:
Enter Number of elements: 7
4 5 6 7 1 2 3
Shortest un-ordered sub-arr: 3
0 Comments