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

Time:06-22

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.

CodePudding user response:

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();
}

CodePudding user response:

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
  • Related