**Example 1:**
Input: N = 5, array[] = {1,2,3,4,5}
Output: True.
Explanation: The given array is sorted i.e Every element in the array is smaller than or equals to its next values, So the answer is True.
**Example 2:**
Input: N = 5, array[] = {5,4,6,7,8}
Output: False.
Explanation: The given array is Not sorted i.e Every element in the array is not smaller than or equal to its next values, So the answer is False.
Here element 5 is not smaller than or equal to its future elements.
Algorithm
class Solution {
// Function to check if the array is sorted
public boolean isSorted(int[] arr, int n) {
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
// If any element is smaller than the previous one, return false
if (arr[j] < arr[i])
return false;
}
}
return true; // Return true if no unsorted elements are found
}
}
public class Main {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
int n = 5;
Solution obj = new Solution();
boolean ans = obj.isSorted(arr, n);
// Output result
if (ans)
System.out.println("True");
else
System.out.println("False");
}
}
Complexity Analysis
Time Complexity: O(N2), as it uses two nested loops to compare every pair of elements in the array.
Space Complexity: O(1), as no extra space is used apart from a few variables.