Program to check if an array is sorted strictly

Published on August 04, 2021
Last updated August 04, 2021

Problem statement

Given an array A of size N write a function that tells if an array is sorted or not.
A strictly sorted array will be in one of the following Forms

a0 < a1 < a2 <…an
a0 > a1 > a2 >…an

Input format

Line 1: Integer T- Number of test cases
Each test case consists of following lines
Test case Line 1: Integer N - Number of elements in the array.
Test case Line 2: N space separated integers representing array elements

Output format

For each test case print a separate line of output, each line should print either TRUE or FALSE(in capital letters) to tell if array is strictly sorted or not

Constrains

1 <= T <= 100
-10 power 6 <= A[i] <= 10 power 4
1 <= N <= 10 power 4

java implementation of the program

import java.util.*;

public class isArraySorted {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int num_of_test_cases = sc.nextInt();
        while (num_of_test_cases > 0) {
            int array_size = sc.nextInt();
            // print true and skip remaining steps if arraysize
            // is equal to 1 as one element is already sorted
            if (array_size == 1) {
                System.out.println("TRUE");
                continue;
            }
            // we are not checking for zero because the problem
            // constrains states that num_of_test_cases will be
            // in the range 1,100
            int[] array_of_numbers = new int[array_size];
            for (int i = 0; i < array_size; i++) {
                array_of_numbers[i] = sc.nextInt();
            }

            // declare two boolean variables representing ascending
            // and descending order with initial value of true
            boolean is_ascending = true;
            boolean is_descending = true;

            for (int i = 1; i < array_size; i++) {
                if (array_of_numbers[i] >= array_of_numbers[i - 1])
                    is_descending = false;

                if (array_of_numbers[i] <= array_of_numbers[i - 1])
                    is_ascending = false;
            }

            if (is_ascending || is_descending) {
                System.out.println("TRUE");
                continue;
            }
            System.out.println("FALSE");
            num_of_test_cases--;
        }
        // close the Scanner
        sc.close();
    }
}


Tags :