Type of array and its maximum element
Given an array, it can be of 4 types
(a) Ascending
(b) Descending
(c) Ascending Rotated
(d) Descending Rotated
Find out which kind of array it is and return the maximum of that array.
(a) Ascending
(b) Descending
(c) Ascending Rotated
(d) Descending Rotated
Find out which kind of array it is and return the maximum of that array.
1- First, check if the whole array is in increasing order, if yes then print arr[n-1]. and return. 2- If above statement doesn't run even single time that means an array is in decreasing order from starting. Two cases arise: a) Check if the whole array is in decreasing order, if yes then print arr[0] and return. (b) Otherwise, the array is descending rotated and the maximum element will be the index before which array was decreasing. 3- If first point partially satisfies that means the whole array is not in increasing order that means an array is ascending rotated and the maximum element will be the point from where it starts decreasing.
public
static
void
findType(
int
arr[])
{
int
i =
0
;
int
n = arr.length;
// Check if the array is in ascending order
while
(i < n-
1
&& arr[i] <= arr[i+
1
])
i++;
// If i reaches to last index that means
// all elements are in increasing order
if
(i == n-
1
)
{
System.out.println(
"Ascending with maximum element = "
+
arr[n-
1
]);
return
;
}
// If first element is greater than next one
if
(i ==
0
)
{
while
(i < n-
1
&& arr[i] >= arr[i+
1
])
i++;
// If i reaches to last index
if
(i == n -
1
)
{
System.out.println(
"Descending with maximum "
+
"element = "
+ arr[
0
]);
return
;
}
// If the whole array is not in decreasing order
// that means it is first decreasing then
// increasing, i.e., descending rotated, so
// its maximum element will be the point breaking
// the order i.e. i so, max will be i+1
if
(arr[
0
] < arr[i+
1
])
{
System.out.println(
"Descending rotated with"
+
" maximum element = "
+ max(arr[
0
], arr[i+
1
]));
return
;
}
else
{
System.out.println(
"Ascending rotated with"
+
" maximum element = "
+ max(arr[
0
], arr[i+
1
]));
return
;
}
}
// If whole array is not increasing that means at some
// point it is decreasing, which makes it ascending rotated
// with max element as the decreasing point
if
(i < n-
1
&& arr[
0
] > arr[i+
1
])
{
System.out.println(
"Ascending rotated with maximum"
+
" element = "
+ max(arr[i], arr[
0
]));
return
;
}
System.out.println(
"Descending rotated with maximum "
+
"element "
+ max(arr[i],arr[
0
]));
}