Checking if an Array is in Ascending or Descending order in a loop

Viewed 361

I need to write a program that checks if the boys (3) are arranged in ascending or descending order by height.

I can use 3 times scanner.nextInt():

int a = scanner.nextInt();

than use if statement :

if (a >= b && b >= c || c >= b && b >= a) {
    System.out.println("true");
} else {
    System.out.println("false");
}

And it's work perfectly.

I also can create an array and check it, but it's not interesting. But I want to try to solve it using for loop for scanning input values within loop and check conditions:

final int numberOfBoys = 3;
boolean result = false;
    
for (int i = 0; i < numberOfBoys; i++) {
    int boyHeight = scanner.nextInt();
    int a = boyHeight;
    if (a >= boyHeight || a <= boyHeight) {
        result = true;
    }
}
    
System.out.println(result);

Here I assigned input value of boyHeight to a variable and compare it with next scanning value, but I always get true result which is wrong.

3 Answers

Here is a way to determine if all three are in descending order, ascending order, or not in order at all.

 1.   Scanner scanner = new Scanner(System.in);
 2.   int[] heights = new int[3];
 3.   heights[0] = scanner.nextInt();
 4.   heights[1] = scanner.nextInt();
 5.   heights[2] = scanner.nextInt();
 6.   
 7.   if (heights[0] >= heights[1] && heights[1] >= heights[2]) {
 8.      System.out.println("descending order");
 9.   } else if (heights[0] <= heights[1] && heights[1] <= heights[2]) {
10.      System.out.println("ascending order");
11.   } else {
12.      System.out.println("not in order");
13.   }

A few notes:

  • line 2: this is hard-coded to 3, obviously it wouldn't work if you want to compare with 4 or some other number
  • lines 3-5: also hard-coded to 3, but easily could be moved into a loop
  • line 7: if item 0 is larger than 1, and 1 is larger than 2, that's clearly "descending". This could be reworked to fit with a loop, but it's perhaps clearer to see this way.
  • line 9: similar to 7, just compare the other direction
  • line 12: this is the case for mixed ordering, neither ascending nor descending

If you want to use a loop, here's an edit to replace lines 2-5:

int totalToCheck = 3;
int[] heights = new int[totalToCheck];
for (int i = 0; i < totalToCheck; i++) {
    heights[i] = scanner.nextInt();
}

Checking if an Array is in Ascending or Descending order in a loop

I want to try solve it using for scanning input values within loop

Solution below allow to determine whether array the order of an array of an arbitrary length without using hard-coded conditions.

Note that storing the user input into an array simultaneously with checking if this array is order violate the first SOLID principle - the Single responsibility principle. The correct way to do that is to first read the array data from the console (which is pretty trivial) and then determine whether this array is ordered - that is the focus of this answer.

Regardless of the number of elements in the array there could be the following cases:

  • Array is sorted in Ascending order;

  • Array is sorted in Descending order;

  • Array is unordered;

  • Since equal values are allowed there could be the case when all elements are equal, i.e. we can't say array is unordered, but at the same it is neither ascending, no descending.

I'm also making an assumption that the given will contain at least 1 element.

public static void determineArrayOrder(int[] arr) {
    
    boolean isAsc = arr[0] < arr[arr.length - 1]; // if array is sorted in ascending order the first element has to be less than the last element
    int previous = arr[0]; // variable that would hold the value of the previously encountered element
    
    for (int i = 1; i < arr.length; i++) { // iteration starts from 1 because `previous` has been initialized with the value of the element at index 0
        int next = arr[i];
        
        if (next < previous && isAsc || next > previous && !isAsc) { // the order doesn't match
            System.out.println("Array is unordered");
            return;
        }
        previous = next;
    }
    // printing the result
    if (arr[0] == arr[arr.length - 1]) {
        System.out.println("impossible to determine the order");
    } else if (isAsc) {
        System.out.println("Array is sorted in Ascending order");
    } else {
        System.out.println("Array is sorted in Descending order");
    }
}

main()

public static void main(String[] args) {
    determineArrayOrder(new int[]{1, 2, 3, 3, 3}); // ASC
    determineArrayOrder(new int[]{7, 5, 3, 3, 5}); // unordered
    determineArrayOrder(new int[]{7, 8, 9, 8, 8}); // unordered
    determineArrayOrder(new int[]{7, 5, 3, 3, 1}); // DSC
    determineArrayOrder(new int[]{9, 9, 9, 9, 9}); // impossible to determine the order
}

Output:

Array is sorted in Ascending order
Array is unordered
Array is unordered
Array is sorted in Descending order
impossible to determine the order

Another way of doing this on the fly is

  1. Read the number of elements (input validation at least 2 values)
  2. Check first 2 values to get the order
  3. Iterate the rest of elements and check if the order is the same
  4. Display the result
public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.print("Input numbers: ");
    int numberOfBoys = scanner.nextInt(); // Read the number of elements in the array
    if (numberOfBoys < 2) { // Validate the input
        System.out.println("Invalid input");
    }
    boolean isAsc = false; // Assume that the sequence is DESC
    boolean isValid = true; // Assume that the sequence is valid
    int previousRead = scanner.nextInt(); // Read first value
    int currentRead = scanner.nextInt(); // Read second value

    if (previousRead < currentRead) { // Check if the first 2 values are ASC
        isAsc = true; // Correct our assumption
    }

    previousRead = currentRead; // Swap the values to prepare for the next read
    // Iterate through the rest of the sequence
    for (int i = 0; i < numberOfBoys - 2; i++) {
        currentRead = scanner.nextInt(); // Read the next value
        // Check if the new value respect the order
        isValid = isAsc ? currentRead >= previousRead : currentRead <= previousRead;
        // if the new value does not follow the order,
        // breaks the loop because we already know the answer and
        // there is no point in reading the rest of the values
        if (!isValid) {
            break;
        }
        previousRead = currentRead; // Swap the values to prepare for the next read
    }

    // Print the conclusion
    if (isValid) {
        if (isAsc) {
            System.out.println("ASC");
        } else {
            System.out.println("DESC");
        }
    } else {
        System.out.println("Unsorted");
    }
}
Related