Check array sorted (non-decreasing)

Check array sorted (non-decreasing)

Easy Java Arrays 21 views
Explanation Complexity

Problem Statement

Task: return true if the array is sorted in non-decreasing order. Compare adjacent elements.

Input Format

An integer n (size of array)
Then n integers (array elements)

Output Format

true if array is sorted in non-decreasing order, otherwise false.

Example

5
1 2 2 4 5
true

Constraints

• n ≥ 1

• Non-decreasing means: arr[i]

Concept Explanation

An array is non-decreasing if no element is greater than the next one.
We only compare adjacent elements

Step-by-Step Explanation

1.Read array size n.

2.Read n elements into the array.

3.Loop from index 0 to n-2.

4.For each index i:

• If arr[i] > arr[i+1], return false.

5.If loop finishes without finding a problem, return true.

Concept Explanation

An array is non-decreasing if no element is greater than the next one.
We only compare adjacent elements

Step-by-Step Explanation

1.Read array size n.

2.Read n elements into the array.

3.Loop from index 0 to n-2.

4.For each index i:

• If arr[i] > arr[i+1], return false.

5.If loop finishes without finding a problem, return true.

Input / Output Format

Input Format
An integer n (size of array)
Then n integers (array elements)
Output Format
true if array is sorted in non-decreasing order, otherwise false.
Constraints
• n ≥ 1

• Non-decreasing means: arr[i]

Examples

Input:
5 1 2 2 4 5
Output:
true

Example Solution (Public)

Java
static boolean isSorted(int[] a){for(int i=1;i<a.length;i++) if(a[i]<a[i-1]) return false;return true;}

Official Solution Code

static boolean isSorted(int[] a){for(int i=1;i<a.length;i++) if(a[i]<a[i-1]) return false;return true;}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.