Reputation: 353
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.
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));
}
Upvotes: 19
Views: 141246
Reputation: 1
The best way to test if an array is sorted or not is this way :
boolean isSorted (int[] arr) {
boolean isIt = true;
int len = arr.length;
for (int i = 0 ; i < arr.length ; i++ ) {
len--;
for (int j = i ; j < len; j++) {
if (arr[i] < arr[j+1]) {isIt = true;}
else {return false;}
}
}
return true;
}
Because if you use the following code you get true for this array which is not correct
int[] test = {5,6,3,4};
for (i = 0; i < a.length; i++); {
if (a[i] < a[i + 1]) {
return true;
}
else {
return false;
}
}
Upvotes: 0
Reputation: 1
In the array, the index value is from 0 to n-1(n is the length of the array). When the loop comes at the last index ie n-1 the value of i+1 is n which is outside the array as the array index is only until n-1 so you are getting an array out of bound exception.
Upvotes: 0
Reputation: 1
public class checksorted {
boolean isSorted(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i] > arr[i + 1]) {
return false;
}
}
return true;
}
Upvotes: -1
Reputation: 175
If an array is not in ascending order or descending order then it's not sorted.
I will check whether neighbour elements are sorted or not. if any element is smaller than its previous element then It's not sorted in ascending order.
public static boolean isAscendingOrder(int[] a)
{
for ( int i = 0; i < a.length - 1 ; i++ ) {
if ( a[i] > a[i+1] )
return false;
}
return true;
}
// Same with Desending order
public static boolean isDescendingOrder(int[] a)
{
for ( int i = 0; i < a.length - 1 ; i++ ) {
if ( a[i] < a[i+1] )
return false;
}
return true;
}
public static boolean isSorted(int[] a)
{
return isAscendingOrder(a) || isDescendingOrder(a);
}
This function checks whether the array is in Sorted order or not irrespective of its order i.e, ascending or descending.
Upvotes: 0
Reputation: 31
public static boolean isSorted(int[] a)
{
int i,count=0;
for(i = 0; i < a.length-1; i++);{
if (a[i] < a[i+1]) {
count=count+1;
}
}
if(count==a.length-1)
return true;
else
return false;
}
public static void main(String[] args)
{
int ar[] = {3,5,6,7};
System.out.println(isSorted(ar));
}
Here,this is code on checking the array is sorted or not, if it is sorted it return true, else false.I hope you understand the approach.
Upvotes: 0
Reputation: 1593
bool checkSorted(int a[], int n) {
for (int i = 1; i < n-1; i++) {
if (a[i] > a[i-1]) {
return false;
}
}
return true;
}
Upvotes: 0
Reputation: 333
If you want to check if the array is sorted DESC or ASC:
boolean IsSorted(float [] temp)
{
boolean result=true,result2=true;
for (int i = 0; i < temp.length-1; i++)
if (temp[i]< temp[i + 1])
result= false;
for (int i = 0; i < temp.length-1; i++)
if (temp[i] > temp[i + 1])
result2= false;
return result||result2;
}
Upvotes: 0
Reputation: 1
boolean checkElements(int arr[], int first, int last) {
while(arr.length > first) {
if(arr[i] > arr[last-1]) {
if(arr[i] > arr[i+1])
return checkElements(arr, first+1, first+2);;
return false;
}else {
if(arr[i] < arr[i+1])
return checkElements(arr, first+1, first+2);
return false;
}
}
return true;
}
Upvotes: 0
Reputation: 29680
For anyone using Java 8 and above, here's a simple one-liner:
public static boolean isSorted(int[] array) {
return IntStream.range(0, array.length - 1).noneMatch(i -> array[i] > array[i + 1]);
}
Or a logically-equivalent alternative:
public static boolean isSorted(int[] array) {
return IntStream.range(0, array.length - 1).allMatch(i -> array[i] <= array[i + 1]);
}
Upvotes: 13
Reputation: 1013
A descending array is also sorted. To account for both ascending and descending arrays, I use the following:
public static boolean isSorted(int[] a){
boolean isSorted = true;
boolean isAscending = a[1] > a[0];
if(isAscending) {
for (int i = 0; i < a.length-1; i++) {
if(a[i] > a[i+1]) {
isSorted = false;
break;
}
}
} else {//descending
for (int i = 0; i < a.length-1; i++) {
if(a[i] < a[i+1]) {
isSorted = false;
break;
}
}
}
return isSorted;
}
Upvotes: 1
Reputation: 3695
The every() method tests whether all elements in the array pass the test implemented by the provided function.
arr.every(function (a, b) {
return a > b;
});
var arr = [1,2,3] // true
var arr = [3,2,1] // false
Upvotes: -4
Reputation: 576
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
Upvotes: 2
Reputation: 17226
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.
}
Upvotes: 37
Reputation: 41
int i;
for(i = 0; i < a.length - 1 && a[i] < a[i+1]; i++){}
return (i == a.length - 1);
Upvotes: 4
Reputation: 109
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;
}
Upvotes: 2
Reputation: 1272
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;
}
}
Upvotes: 0
Reputation: 178263
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 ++){
Upvotes: 3