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.java
file in the WebIDE editor.
-
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.");
}
}
}
-
Save the file (Ctrl+S or Cmd+S).
-
In the Terminal, make sure you are in the ~/project
directory:
cd ~/project
-
Compile the modified program:
javac CheckOrder.java
No output indicates successful compilation.
-
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.