Blog coding and discussion of coding about JavaScript, PHP, CGI, general web building etc.

Wednesday, February 3, 2016

Check if an array is sorted, return true or false

Check if an array is sorted, return true or false


I am writing an easy program the just returns true if an array is sorted else false and I keep getting an exception in eclipse and I just can't figure out why. I was wondering if someone could take a look at my code and kind of explain why I'm getting an array out of bounds exception. Thank you for your help in advanced.

public static boolean isSorted(int[] a)   {        int i;      for(i = 0; i < a.length; i ++);{          if (a[i] < a[i+1]) {              return true;          } else {              return false;             }      }  }  public static void main(String[] args)  {            int ar[] = {3,5,6,7};            System.out.println(isSorted(ar));   }  

Answer by Richard Tingle for Check if an array is sorted, return true or false


Let's look at a cleaner version of the loop you constructed:

for (i = 0; i < a.length; i++) {       if (a[i] < a[i + 1]) {          return true;      }      else {          return false;      }  }  

I should first point out the syntax error in the original loop. Namely, there is a semicolon (;) before the curly brace ({) that starts the body of the loop. That semicolon should be removed. Also note that I reformatted the white-space of the code to make it more readable.

Now let's discuss what happens inside your loop. The loop iterator i starts at 0 and ends at a.length - 1. Since i functions as an index of your array, it makes sense pointing out that a[0] is the first element and a[a.length - 1] the last element of your array. However, in the body of your loop you have written an index of i + 1 as well. This means that if i is equal to a.length - 1, your index is equal to a.length which is outside of the bounds of the array.

The function isSorted also has considerable problems as it returns true the first time a[i] < a[i+1] and false the first time it isn't; ergo it does not actually check if the array is sorted at all! Rather, it only checks if the first two entries are sorted.

A function with similar logic but which checks if the array really is sorted is

public static boolean isSorted(int[] a) {  // Our strategy will be to compare every element to its successor.  // The array is considered unsorted  // if a successor has a greater value than its predecessor.  // If we reach the end of the loop without finding that the array is unsorted,  // then it must be sorted instead.    // Note that we are always comparing an element to its successor.  // Because of this, we can end the loop after comparing   // the second-last element to the last one.  // This means the loop iterator will end as an index of the second-last  // element of the array instead of the last one.      for (int i = 0; i < a.length - 1; i++) {          if (a[i] > a[i + 1]) {              return false; // It is proven that the array is not sorted.          }      }        return true; // If this part has been reached, the array must be sorted.  }  

Answer by EyeOfTheHawks for Check if an array is sorted, return true or false


a[i+1] when i == a.length will give you that error.

For example, in an array of length 10, you have elements 0 to 9.

a[i+1] when i is 9, will show a[10], which is out of bounds.

To fix: for(i=0; i < a.length-1;i++)

Also, your code does not check through the whole array, as soon as return is called, the checking-loop is terminated. You are simply checking the first value, and only the first value.

AND, you have a semi-colon after your for loop declaration, which is also causing issues

Answer by rgettman for Check if an array is sorted, return true or false


With this expression, a[i+1], you are running off the end of the array.

If you must compare to the next element, then stop your iteration 1 element early (and eliminate the semicolon, which Java would interpret as your for loop body):

// stop one loop early ---v       v--- Remove semicolon here  for(i = 0; i < a.length - 1; i ++){  

Answer by dtgee for Check if an array is sorted, return true or false


You shouldn't use a[i+1] because that value may or may not go off the array.

For example:

A = {1, 2, 3}  // A.length is 3.  for(i = 0; i < a.length; i ++) // A goes up to 3, so A[i+1] = A[4]  

To fix this, simply stop the loop one early.

int i;  for(i = 0; i < a.length - 1; i ++);{        if (a[i] < a[i+1]) {            return true;      }else{          return false;        }    }  

Answer by savanibharat for Check if an array is sorted, return true or false


To check whether array is sorted or not we can compare adjacent elements in array.

Check for boundary conditions of null & a.length == 0

public static boolean isSorted(int[] a){            if(a == null) {          //Depends on what you have to return for null condition          return false;      }      else if(a.length == 0) {          return true;      }      //If we find any element which is greater then its next element we return false.      for (int i = 0; i < a.length-1; i++) {          if(a[i] > a[i+1]) {              return false;          }                 }      //If array is finished processing then return true as all elements passed the test.      return true;  }  

Answer by Shogun for Check if an array is sorted, return true or false


int i;  for(i = 0; i < a.length - 1 && a[i] < a[i+1]; i++){}  return (i == a.length - 1);  
  • only accesses array elements, last part of end condition are not processed if first part ist false
  • stops on first not sorted element


Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72

0 comments:

Post a Comment

Popular Posts

Powered by Blogger.