DEV Community

Chhavi Joshi
Chhavi Joshi

Posted on

Array basic

So I was learning basics of java, where I found a question to check if an array is sorted or not. For this I wrote the following code:

Image description

let's break this code down!

  1. First I made an array and assigned values to it as well.
  2. Then I created flags isAscending and isDescending and initialized them as true. (This was necessary to compare the whole array, you'll understand as i move forward)
  3. Then I traversed the array using for loop and checked 2 conditions:
  • for every element check if its preceeding element is greater, if yes instead of writing isAscending = true, write isDescending = false.
  • similarly check for arr[i] > arr[i+1], and assign isAscending = false.
  1. Then at the I end used if else to print if the array is sorted or not.

This was basic algo now lets understand why I made it this way.

at first I wrote this code:
for(int i = 0; i < arr.length-1; i++){
if(arr[i] < arr[i+1]){
System.out.println("array is sorted in ascending order");
}
else if(arr[i] > arr[i+1]){
System.out.println("array is sorted in descending order");
}
else{
System.out.println("array is not sorted");
}
}
but this code checks individual elements instead of checking the whole array and displays an output for every two consecutive elements.

so i used flags instead and that too with condition = false,
this checks two elements and traverses whole array this way, and if the condition of either isAscending or isDescending remains true until the end uses last if else statement to print output.

Top comments (0)