How to Check If an Array Is Sorted in Java

JavaJavaBeginner
Practice Now

Introduction

In this lab, you will learn how to check if an array of numbers is sorted in Java. We will explore the fundamental concept of comparing adjacent elements, which is a core idea in many sorting algorithms. You will learn how to check for both ascending and descending order, and how to handle cases where elements are equal. By the end of this lab, you will have a solid understanding of the logic required to determine if an array is sorted.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("Java")) -.-> java/BasicSyntaxGroup(["Basic Syntax"]) java(("Java")) -.-> java/DataStructuresGroup(["Data Structures"]) java/BasicSyntaxGroup -.-> java/operators("Operators") java/BasicSyntaxGroup -.-> java/if_else("If...Else") java/DataStructuresGroup -.-> java/sorting("Sorting") subgraph Lab Skills java/operators -.-> lab-560004{{"How to Check If an Array Is Sorted in Java"}} java/if_else -.-> lab-560004{{"How to Check If an Array Is Sorted in Java"}} java/sorting -.-> lab-560004{{"How to Check If an Array Is Sorted in Java"}} end

Compare Adjacent Elements for Sorting

In this step, we will start exploring the fundamental concept of comparing adjacent elements, which is a core idea in many sorting algorithms. Sorting is the process of arranging elements in a specific order, such as ascending or descending.

Imagine you have a list of numbers, and you want to sort them from smallest to largest. One simple way to start is by looking at two numbers next to each other and deciding which one should come first.

Let's create a simple Java program to demonstrate this idea. We will create a class that compares two numbers.

  1. Open the HelloJava.java file in the WebIDE editor if it's still open. We will modify this file for our new program.

  2. Replace the entire contents of the file with the following code:

    public class CompareNumbers {
        public static void main(String[] args) {
            int number1 = 15;
            int number2 = 10;
    
            System.out.println("Comparing " + number1 + " and " + number2 + ":");
    
            if (number1 > number2) {
                System.out.println(number1 + " is greater than " + number2);
            } else if (number1 < number2) {
                System.out.println(number1 + " is less than " + number2);
            } else {
                System.out.println(number1 + " is equal to " + number2);
            }
        }
    }

    Let's look at the new parts of this code:

    • public class CompareNumbers: We've changed the class name to CompareNumbers to better reflect what the program does. Remember, the file name must match the class name, so we will need to rename the file later.
    • int number1 = 15; and int number2 = 10;: These lines declare two integer variables, number1 and number2, and assign them initial values.
    • System.out.println("Comparing " + number1 + " and " + number2 + ":");: This line prints a message indicating which numbers are being compared.
    • if (number1 > number2): This is an if statement. It checks if the condition inside the parentheses (number1 > number2) is true. If it is, the code inside the curly braces {} immediately following the if statement is executed.
    • else if (number1 < number2): This is an else if statement. If the condition in the if statement was false, this condition (number1 < number2) is checked. If it's true, the code inside its curly braces is executed.
    • else: This is an else statement. If neither the if nor the else if conditions were true, the code inside the else block is executed.
    • System.out.println(...): These lines print messages based on the comparison result.
  3. Save the file (Ctrl+S or Cmd+S).

  4. Now, we need to rename the file to match the new class name. In the Terminal, make sure you are in the ~/project directory:

    cd ~/project
  5. Rename the file using the mv command:

    mv HelloJava.java CompareNumbers.java

    This command moves (renames) the file HelloJava.java to CompareNumbers.java.

  6. Now, compile the new program:

    javac CompareNumbers.java

    If the compilation is successful, you should see no output.

  7. Finally, run the compiled program:

    java CompareNumbers

    You should see the output indicating the comparison result:

    Comparing 15 and 10:
    15 is greater than 10

You have successfully created and run a Java program that compares two adjacent elements and prints the result. This simple comparison is a building block for more complex sorting algorithms.

Check Ascending and Descending Order

In the previous step, we learned how to compare two numbers. Now, let's expand on that to check if a pair of adjacent numbers is in ascending or descending order. This is another fundamental concept when thinking about sorting.

Ascending order means arranging elements from smallest to largest (e.g., 1, 5, 10). Descending order means arranging elements from largest to smallest (e.g., 10, 5, 1).

We will modify our CompareNumbers.java program to check for these specific orderings.

  1. Open the CompareNumbers.java file in the WebIDE editor.

  2. Replace the existing code with the following:

    public class CheckOrder {
        public static void main(String[] args) {
            int number1 = 15;
            int number2 = 10;
    
            System.out.println("Checking order of " + number1 + " and " + number2 + ":");
    
            if (number1 < number2) {
                System.out.println("The numbers are in ascending order.");
            } else if (number1 > number2) {
                System.out.println("The numbers are in descending order.");
            } else {
                System.out.println("The numbers are equal.");
            }
        }
    }

    Here's what we've changed:

    • public class CheckOrder: We've changed the class name again to CheckOrder. We will need to rename the file to match.
    • The if condition now checks if number1 is less than number2. If true, it means they are in ascending order.
    • The else if condition checks if number1 is greater than number2. If true, they are in descending order.
    • The else block handles the case where the numbers are equal.
  3. Save the file (Ctrl+S or Cmd+S).

  4. In the Terminal, make sure you are in the ~/project directory:

    cd ~/project
  5. Rename the file to match the new class name:

    mv CompareNumbers.java CheckOrder.java
  6. Compile the modified program:

    javac CheckOrder.java

    Again, no output means successful compilation.

  7. Run the program:

    java CheckOrder

    With number1 = 15 and number2 = 10, the output should be:

    Checking order of 15 and 10:
    The numbers are in descending order.
  8. Let's quickly modify the numbers to see the ascending case. Open CheckOrder.java in the editor and change the values:

    public class CheckOrder {
        public static void main(String[] args) {
            int number1 = 5; // Changed from 15
            int number2 = 8; // Changed from 10
    
            System.out.println("Checking order of " + number1 + " and " + number2 + ":");
    
            if (number1 < number2) {
                System.out.println("The numbers are in ascending order.");
            } else if (number1 > number2) {
                System.out.println("The numbers are in descending order.");
            } else {
                System.out.println("The numbers are equal.");
            }
        }
    }
  9. Save the file.

  10. Compile the program again:

    javac CheckOrder.java
  11. Run the program:

    java CheckOrder

    Now the output should reflect the ascending order:

    Checking order of 5 and 8:
    The numbers are in ascending order.

You have successfully modified the program to check if two adjacent numbers are in ascending or descending order. This is a crucial step in understanding how sorting algorithms determine the correct position of elements.

Handle Equal Elements

In the previous steps, we compared two numbers and checked if they were in ascending or descending order. We also included a case for when the numbers are equal. In this step, we will focus specifically on handling the scenario where adjacent elements are the same.

While sorting, the order of equal elements usually doesn't matter for the final sorted result, but it's important for our comparison logic to correctly identify this case. Our current CheckOrder.java program already handles this with the else block. Let's explicitly test this case.

  1. Open the CheckOrder.java file in the WebIDE editor.

  2. Modify the values of number1 and number2 to be equal:

    public class CheckOrder {
        public static void main(String[] args) {
            int number1 = 7; // Changed to 7
            int number2 = 7; // Changed to 7
    
            System.out.println("Checking order of " + number1 + " and " + number2 + ":");
    
            if (number1 < number2) {
                System.out.println("The numbers are in ascending order.");
            } else if (number1 > number2) {
                System.out.println("The numbers are in descending order.");
            } else {
                System.out.println("The numbers are equal.");
            }
        }
    }
  3. Save the file (Ctrl+S or Cmd+S).

  4. In the Terminal, make sure you are in the ~/project directory:

    cd ~/project
  5. Compile the modified program:

    javac CheckOrder.java

    No output indicates successful compilation.

  6. Run the program:

    java CheckOrder

    With both numbers set to 7, the output should now be:

    Checking order of 7 and 7:
    The numbers are equal.

This confirms that our program correctly identifies when the two adjacent numbers are equal. Handling this case is important for the completeness of our comparison logic.

In the context of sorting algorithms, when adjacent elements are equal, they are already in a valid relative order (both ascending and descending could be considered true depending on the strictness, but typically they are just considered "equal" and no swap is needed).

You have now successfully tested the case where adjacent elements are equal, completing our exploration of comparing two adjacent numbers for sorting purposes.

Summary

In this lab, we began by exploring the fundamental concept of comparing adjacent elements, a core idea in sorting algorithms. We learned how to create a simple Java program to compare two numbers and determine if one is greater than, less than, or equal to the other. This involved understanding basic Java syntax for variable declaration, assignment, and conditional statements (if, else if, else). We also practiced modifying existing Java files and learned the importance of matching the class name with the file name.

Building upon the concept of comparing adjacent elements, we then extended our understanding to check for both ascending and descending order within a sequence of numbers. This involved applying the comparison logic iteratively to multiple elements. Finally, we addressed the scenario of handling equal elements during the sorting check, ensuring our logic correctly accounts for cases where adjacent elements have the same value. These steps provided a foundational understanding of how to programmatically determine if an array is sorted in Java.