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.
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.
Open the
HelloJava.javafile in the WebIDE editor if it's still open. We will modify this file for our new program.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 toCompareNumbersto 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;andint number2 = 10;: These lines declare two integer variables,number1andnumber2, 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 anifstatement. It checks if the condition inside the parentheses (number1 > number2) is true. If it is, the code inside the curly braces{}immediately following theifstatement is executed.else if (number1 < number2): This is anelse ifstatement. If the condition in theifstatement was false, this condition (number1 < number2) is checked. If it's true, the code inside its curly braces is executed.else: This is anelsestatement. If neither theifnor theelse ifconditions were true, the code inside theelseblock is executed.System.out.println(...): These lines print messages based on the comparison result.
Save the file (Ctrl+S or Cmd+S).
Now, we need to rename the file to match the new class name. In the Terminal, make sure you are in the
~/projectdirectory:cd ~/projectRename the file using the
mvcommand:mv HelloJava.java CompareNumbers.javaThis command moves (renames) the file
HelloJava.javatoCompareNumbers.java.Now, compile the new program:
javac CompareNumbers.javaIf the compilation is successful, you should see no output.
Finally, run the compiled program:
java CompareNumbersYou 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.
Open the
CompareNumbers.javafile in the WebIDE editor.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 toCheckOrder. We will need to rename the file to match.- The
ifcondition now checks ifnumber1is less thannumber2. If true, it means they are in ascending order. - The
else ifcondition checks ifnumber1is greater thannumber2. If true, they are in descending order. - The
elseblock handles the case where the numbers are equal.
Save the file (Ctrl+S or Cmd+S).
In the Terminal, make sure you are in the
~/projectdirectory:cd ~/projectRename the file to match the new class name:
mv CompareNumbers.java CheckOrder.javaCompile the modified program:
javac CheckOrder.javaAgain, no output means successful compilation.
Run the program:
java CheckOrderWith
number1 = 15andnumber2 = 10, the output should be:Checking order of 15 and 10: The numbers are in descending order.Let's quickly modify the numbers to see the ascending case. Open
CheckOrder.javain 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."); } } }Save the file.
Compile the program again:
javac CheckOrder.javaRun the program:
java CheckOrderNow 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.
Open the
CheckOrder.javafile in the WebIDE editor.Modify the values of
number1andnumber2to 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."); } } }Save the file (Ctrl+S or Cmd+S).
In the Terminal, make sure you are in the
~/projectdirectory:cd ~/projectCompile the modified program:
javac CheckOrder.javaNo output indicates successful compilation.
Run the program:
java CheckOrderWith 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.



